How to embed multiple jQuery line of code in custom HtmlHelpers ASP.NET MVC
- by embarus
I 've tried to create my own HTML Helper which work fine for my need but I can't embed many lines
of jQuery code in my extension HtmlHelpers class. I've tried @ literal for jQuery code I doesn't work or I need to escape every line of code that I thing I not good for
multiple line of code. I don't know if there is another way to achieve this problem like <<
Therefore, I need to include jQuery plugin file and put implement script
after HTML tag. I find it would be convenience if I could put every in HTML helper and put a single line of code in aspx page for example
<%= Html.ParentChildSelectList(string parentName, string  childName, IEnumerable parentViewData, IEnumerable childViewData,
int parentSize, in childSize) %
The following code is the way that I used now.
the .aspx page   
   
        
            Category
        
         model.CategoryID)%
        , new { size = 10 })%
    
        model.SubcategoryID,"subcategory") % model.SubcategoryID)%
        , new { size = 10 })%
    
<script type="text/javascript">
jQuery.sarapadchang.parentChildSelectList(
   {
   parentId : "CategoryID" ,
   childId : "SubcategoryID",
   actionName : "GetSubcategoryList",
   controllerName : "Json"
   }
   );
   </script>
I put  in head tag to include ParentChildSelectList.js
the following  code for ParentChildSelectList.js
(function($) {
$.sarapadchang = {
    parentChildSelectList: function(options) {
        // $("#CategoryID option").click(function()
        $("#" + options.parentId).find("option").click(function() {
            $("#" + options.childId).empty(); //clear data
            $("#" + options.childId).append('<option>loading...</option>');
            $.post("/" + options.controllerName + "/" +  options.actionName + "/" + $(this).attr('value'), "", function(data) {
                var html = "";
                $.each(data, function(index, entry) {
                    html +=
           '<option value="' +
            entry['Value'] +
            '">' +
            entry['Text'] +
            '</option>';
                }
            );
                $("#" + options.childId).empty()
                $("#" + options.childId).append(html);
            }, "json"); //end getJson
        });
})(jQuery);
To illustrate you, I've attached simple solution, please follow this link.
http://www.thaileaguefc.net/ParentChildSelectList.rar
Please accept my apologies if my English is difficult to understand.
I am looking forward to hearing from you.
Your faithfully,
Theeranit