Returning an EditorTemplate as a Partial View from a Controller
Asked Answered
P

1

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.

Portauprince answered 6/12, 2011 at 16:18 Comment(2)
Why don't you just use EditorFor?Inappropriate
I am initially. I am posting my form with an AJAX call, when the form is invalid I need to return it as a partial view and replace the contentsPortauprince
V
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);
}
Vincenza answered 6/12, 2011 at 16:36 Comment(5)
Can't you do that in the controller too?Inappropriate
@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.Vincenza
Ha I was just about to post the answer myself after finding this. You can do it in the controller too actually.Portauprince
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.Portauprince
Darin, I love your answers. Every time I have problem I can find best answer here, your answer. Thank you a lot)Albumenize

© 2022 - 2024 — McMap. All rights reserved.