I would like to return an EditorTemplate from my controller as a Partial View.
I am currently doing:
public ActionResult Create([Bind(Prefix="Create")]CreateViewModel model)
{
return PartialView("~/Views/Shared/EditorTemplates/Template.cshtml", model);
}
The problem is that after I do this the Create_
prefix goes away from my view. Is there a way to return an editor template as a partial view and retain the prefix?
Index.cshtml @model IndexViewModel
@using(Html.BeginForm("Create"))
{
@Html.EditorFor(m => m.Create, "Template")
<input type="submit" value="Save" />
}
I am submitting this form with an AJAX call. When I originally call EditorFor, all of the fields have a prefix of Create_
. However, after I submit the form and return this PartialView, the prefix is lost.
In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.
To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.
To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.
Since the template wasn't invoked in the context of the main view it loses its context. You could define the prefix in this case as follows:
public ActionResult Create([Bind(Prefix="Create")]CreateViewModel model)
{
ViewData.TemplateInfo.HtmlFieldPrefix = "Create";
return PartialView("~/Views/Shared/EditorTemplates/Template.cshtml", model);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With