Search code examples
c#asp.net-mvc-2partial-viewseditortemplates

Returning an EditorTemplate as a PartialView in an Action Result


I have a model similar to this:

public class myModel 
{
    public ClassA ObjectA {get; set;}
    public ClassB ObjectB {get; set;}
}

In my main view, I have tags similar to this:

<div id="section1">
    <%=Html.EditorFor(m => m.ObjectA)%>
</div>
<div id="section2">
    <%=Html.EditorFor(m => m.ObjectB)%>
</div>

ClassA and ClassB both have Editor templates defined.

I created some JavaScript that makes an Ajax call to reload the section1 div. I want the action method to return the editor for ObjectA, ClassA.ascx that is in the EditorTemplates folder.

I have the following in my Action method:

public ActionResult GetData(int input) 
{
    // Process input here and create modelData

    return PartialView("ClassA", modelData);
}

This gives an error because it cannot find the ClassA view.

My solution has been to create a PartialView in the Views folder called "GetData" and my return renders the GetData view. The GetData view has only one line of code:

<%=Html.RenderForModel()%>

This does work, but I was wondering if there was a way for an action method to return and editor template?


Solution

  • return PartialView("~/EditorTemplates/ClassA.ascx", modelData);