Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an EditorTemplate as a Partial View from a Controller

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.

like image 417
Dismissile Avatar asked Dec 06 '11 16:12

Dismissile


People also ask

Can we return partial view in MVC?

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.

Can we return partial view from action method?

To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.

How to create partial views in mvc?

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.


1 Answers

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);
}
like image 174
Darin Dimitrov Avatar answered Sep 22 '22 09:09

Darin Dimitrov