suomi-dev
suomi-dev

Reputation: 868

How to render MVC Custom Helper through jQuery MVC4

I want to pass jQuery object(List) to MVC4 custom HTML Helper.

My view something like this:

<script type="text/javascript">
$(document).ready(function () {
    var datafilterList = GetDataFilter('@Url.Action("GetJsonDataFilter")'); // this is external file ajax call and I am getting the data pulled from controller. all ok here.
    @Html.DataFilterFor(datafilterList) // how to pass datafilterList and call custom helper??
});
</script>

My Helper Class:

public static class DataFilter
{
    public static MvcHtmlString DataFilterFor(this HtmlHelper html, List<View_webpages_DataFilter> DataFilterList)
    {
        StringBuilder sb = new StringBuilder();
        // TODO: Create the form and render html - I removed the unnecessary html code
        return new MvcHtmlString(sb.ToString());
    }
}

Please can any one tell me how do I pass the jquery object datafilterList to mvc custom helper?

Thank you

Upvotes: 0

Views: 1457

Answers (1)

user3559349
user3559349

Reputation:

You cant. Razor code (the helper) runs on the server when the view is created and before it is sent to the browser. Javascript runs on the browser and as no concept of what a html helper is.

Even if theoretically this was possible, what you are doing is sending a page to the server, then oops!, I forgot some data so go back to the server and return it, and then oops again, what I really wanted was some html, so go back to the server and return it. Why all these round trips when you could have done it once when the page was being created.

Either:

  1. Get what ever the data is returned by GetDataFilter() in the action method you are using to generate this view and render the html (either directly in he view or call an child action to include a partial view); or if you prefer AJAX

  2. Have the GetJsonDataFilter() function return the html you want (or call another method that returns the html) and then in its success function, add the html to the DOM

Upvotes: 3

Related Questions