Common ASP.NET MVC Partial View Template

I have a partial idea that I want to be general. According to this question , partial representations cannot be shared. So instead, I made the HtmlHelper extension, which processes the parts for which I want a security type, and then defers the rest to a real partial view.

Usually my helper is called when a page loads, which works fine, but sometimes I want to add a line or something through AJAX. When this happens, the controller cannot use my "partial view", since it does not have access to the HtmlHelper.

Besides a partial view with a model like object , is there anything I can do?

I use Razor if this is important.

A simplified version of what I'm doing:

 public static MvcHtmlString DoStuff<T>(this HtmlHelper html, IEnumerable<T> data, Func<T, ViewModelType> StronglyTypedFn, string PartialName) { // the pre- and post-processing for the partial view is complex enough I'd like // to encapsulate it. But I want the encapsulation to include the safety // benefits that generics give. var mappedData = data.Select(StronglyTypedFn); string htmlData = ""; foreach(var model in mappedData){ htmlData += html.Partial(PartialName, model); } htmlData += "some boilerplate footer html"; return htmlData; } 

I understand that in this example I have so few lines of code outside the partial view that it seems pointless to have a helper, but in my real example it is more complicated.

Now, in ajax call, I want to return Html.DoStuff() . But I can not, because this requires access to the HtmlHelper, and the helper is not available inside the controller.

+4
source share
2 answers

You may have a simple action method that calls a partial instance of a model instance

 public PartialViewResult Single(string partialName) { return PartialView(partialName); } 
0
source

Instead of an object, you can use a view with a dynamic type.

But ... There seems to be some kind of misunderstanding, because the controller should not even try to display the view. Could you send the controller code?

A better option is an IMO that returns a JsonResult for your ajax request and adding client-side rows / rows using JS.

0
source

Source: https://habr.com/ru/post/1340057/


All Articles