Display AJAX controller action result using HtmlHelpers - asp.net-mvc

I have a fairly complex object which has some C# code written to render it as HTML in various views.
There is also a view which can call an AJAX method of a controller, which returns the complex object serialized to JSON which should then be displayed.
This seems to leave me requriring complicated duplicate code to render the resulting JSON as HTML using Javascript/jQuery.
The obvious solution is to render the HTML in the controller action and return this from the AJAX call. However this seems in violation of the MVC pattern so not really a good option.
Is there a different way I can render the object returned from the AJAX method making use of the existing C# code?
Thanks.

Create a PartialView to which you render the object, and return that.

As mentioned, either create a PartialView user control and return that, which you can inject the HTML in nicely (returns the HTML as a string) or you can use a templating option in JQuery or something else to do the UI generation for you.
HTH.

Related

What is difference between partial and render partial view ?

I am very new in asp.net MVC kindly let me know where is should use partial view and where i should Render Partial view . Thanks in advance
This link might help.
Html.RenderPartial
This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
This method returns void.
Simple to use and no need to create any action.
RenderPartial method is useful when the displaying data in the partial view is already in the corresponding view model.
For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
#{Html.RenderPartial("_Comments");}
This method is faster than Partial method since its result is directly written to the response stream which makes it fast.
Html.Partial
Renders the partial view as an HTML-encoded string.
This method result can be stored in a variable, since it returns string type value.
Simple to use and no need to create any action.
Like RenderPartial method, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model.
For example: In a blog to show comments of an article, you can use Partial method since an article information with comments are already populated in the view model.
#Html.Partial("_Comments")
Both of these helper method are used for rendering partial views
Both have different syntax in razor view #Html.Partial("_student", items) and {Html.RenderPartial("_student", items);}, since render partial return void and the output is written directly to output stream, it has different syntax than Partial.
Syntax in web from view
<%:Html.Partial("_student") %> and <% Html.RenderPartial("_student"); %>
Partial Returns MVCHtmlString, which can be assigned to variables.
Performance wise Render partial is better as it writes directly to output stream.
And of-course you can find a lot of references online and within stack overflow to read

How to render a controller's action result to string?

according to the ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action I'm can render a View to a string. But, is it possible to invoke an action inside the controller and render the result to a string ?
What I tend to do for things like this is return a PartialView which will have any of the HTML I need for the JavaScript to use. Keep in mind that in HTTP, everything is text already, so you don't need to do something special to render the result to a string to return to an AJAX call.
I'll have a PartialView which has the HTML I need, pass it back to the Ajax call using something like return PartialView("ViewName", model), then do whatever I need to on the client side - such as appending that HTML to a node in the DOM.

Razor: #Html.Partial() vs #RenderPage()

What is the appropriate way of rendering a child template?
And what's the difference? Both seem to work for me.
And why does #Html.RenderPartial() no longer work?
Html.Partial("MyView")
Renders the "MyView" view to an MvcHtmlString. It follows the standard rules for view lookup (i.e. check current directory, then check the Shared directory).
Html.RenderPartial("MyView")
Does the same as Html.Partial(), except that it writes its output directly to the response stream. This is more efficient, because the view content is not buffered in memory. However, because the method does not return any output, #Html.RenderPartial("MyView") won't work. You have to wrap the call in a code block instead: #{Html.RenderPartial("MyView");}.
RenderPage("MyView.cshtml")
Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like Html.RenderPartial(). You can supply any model you like to the view by including it as a second parameter
RenderPage("MyView.cshtml", MyModel)
I prefer
#RenderPage("_LayoutHeader.cshtml")
Over
#{ Html.RenderPartial("_LayoutHeader"); }
Only because the syntax is easier and it is more readable. Other than that there doesn't seem to be any differences functionality wise.
EDIT: One advantage of RenderPartial is you don't have to specify the entire path or file extension it will search the common places automatically.
The RenderPartial method doesn’t return HTML markup like most other helper methods. Instead, it writes
content directly to the response stream, which is why we must call it like a complete line of C#, using a semicolon.
This is slightly more efficient than buffering the rendered HTML from the partial view, since it will be written to the
response stream anyway. If you prefer a more consistent syntax, you can use the Html.Partial method, which
does exactly the same as the RenderPartial method, but returns an HTML fragment and can be used as
#Html.Partial("Product", p).
We can also pass model using partial views. #Html.Partial("MyView","MyModel");
#RenderPages()
The above does not work in ASP.NET MVC. It only works in WebPages.
#Html.Partial("_Footer")
You will need to use the above in ASP.NET MVC.
For ASP.NET Core 7. In the Shared folder make partial file then user this following code
<partial name="_NavBar" />

Asp.Net WriteSubsitution vs PartialView - the right way

I have a partial view that should not be cached in a output cached MVC view.
Usually you write non-cached content by using Response.WriteSubstitution.
The problem is that WriteSubstitution takes as a parameter a HttpResponseSubstitutionCallback callback which looks like this:
public delegate string HttpResponseSubstitutionCallback(System.Web.HttpContext context)
This is where things get complicated since there is no easy/fun way to generate the html on the fly.
You have to do a hack like this.
So the question is: Is there an easier way to make a partial view not cached ?
See Phil Haack's article on donut caching in MVC. Phil takes advantage of the existing API to create a new HtmlHelper method to provide a callback that can render the non-cached code. His supplies an anonymous method to the helper to specify the callback. To get this to work unchanged, you'll still need to have a method that renders a partial view to a string, though I think it would be easier to do in an HtmlHelper -- just look at the source for RenderPartial and RenderPartialInternal and see what changes would be needed to write it to a MemoryStream instead of the Response -- I believe it would be the same code except you'd supply your stream instead of the Response output stream, then convert your stream to a string.
It might look like this:
<%= Html.Substitute( cb => Html.RenderToString( "Partial" ) ) %>
Phil indicates that it might make it in to ASP.NET MVC 1.0, but I think it's only available in the MvcFutures assembly.
In MVC2 we can use Html.Action to easily obtain the substituted html. Yeeeeiii
But Response.WriteSubstitotion is not working anymore. Aaaahhhh

Passing object from view to controller

Is there a way to pass a object, specifically a form_builder object used in a view, to an action in the controller? I am using a link_to_remote and want to update a variable in the controller and then add a new nested form element to my form via a render :update block.
If I pass it as a param, it gets converted string and I can't seem to successfully pass a locals hash to the controller either.
No, you cannot pass an object from the view to the controller.
All your logic should happen in the controller and model and at the end of the process the view renders the result in the browser or other places.
You can only use params, whatever you need to send to controller, must be serialized inside params. I'm sure you don't need to send whole form_builder object, send there just what is needed to construct new "subform"
BTW you should construct your views and controllers to work without any ajax, and then progressively enhance your forms and controllers to also support ajax. RJS and render :update is bad practice and should be avoided. find someone who understands javascript instead of writing pseudocode with Rails' RJS

Resources