Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Mike Therien Avatar asked Mar 03 '10 18:03

Mike Therien


3 Answers

Bonus points for gift wrapping:

public class CustomControllerBase : Controller {     public PartialViewResult EditorFor<TModel>(TModel model)     {         return PartialView("EditorTemplates/" + typeof(TModel).Name, model);     }      public PartialViewResult DisplayFor<TModel>(TModel model)     {         return PartialView("DisplayTemplates/" + typeof(TModel).Name, model);     } } 

Have the controller (called, say, MyController) inherit from CustomControllerBase, and then:

public ActionResult MyAction(int id) {     return EditorFor(new MyViewModel(id)); } 

The code will be looking for "~/Views/MyController/EditorTemplates/MyViewModel.ascx".

like image 107
anewcomer Avatar answered Oct 19 '22 01:10

anewcomer


return PartialView("~/EditorTemplates/ClassA.ascx", modelData); 
like image 23
Darin Dimitrov Avatar answered Oct 19 '22 02:10

Darin Dimitrov


this worked for me (mvc 4)

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

    return PartialView("EditorTemplates/ClassA", modelData);
}
like image 45
Daniel Dušek Avatar answered Oct 19 '22 01:10

Daniel Dušek