15

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.

Tseng
  • 61,549
  • 15
  • 193
  • 205
Dismissile
  • 32,564
  • 38
  • 174
  • 263

1 Answers1

26

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);
}
Chris
  • 3,210
  • 1
  • 33
  • 35
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Can't you do that in the controller too? – SLaks Dec 06 '11 at 16:39
  • @SLaks, yes, you can and it is an excellent idea and far better solution than doing it in the template. Will update my post. Thanks. – Darin Dimitrov Dec 06 '11 at 16:42
  • Ha I was just about to post the answer myself after finding this. You can do it in the controller too actually. – Dismissile Dec 06 '11 at 16:42
  • I might create some utility method that will inspect a model looking for a Bind attribute, if it finds one that has a Prefix, it will set the prefix to that value. – Dismissile Dec 06 '11 at 16:44
  • Darin, I love your answers. Every time I have problem I can find best answer here, your answer. Thank you a lot) – Ivan Korytin Jan 29 '13 at 12:55