ASP.NET MVC reusing Action with different Prefix?
I have this Action:
public ActionResult AddCategory(Category newCategory)
{
...//newCategory.Name is filled up
return new Json(true);
}
And a view that post at this Action:
@using(Html.BeginForm)
{
@Html.TextBoxFor(Model.Name)
.....
}
Now I want to reuse this Action, but in another page. But in this new View, I already have a Html.TextBox("name") at another . Its a kind of DashBoard.
This new View, have a property NewCategory inside the Model:
public class MyViewModel
{
public Category NewCategory{get;set;}
}
If I do this:
@using(Ajax.BeginForm)
{
@Html.TextBoxFor(Model.NewCategory.Name)
.....
}
Wont work, because my action dont expect any Prefix, in this case NewCategory.
Of course, I can manually call the Action, but doing this I lost built-in validation(I am using DataAnnotation with Unobtrusive validation).
Its a scenario that I fall from time to time
The best choice that I have now is duplicate the Action:
public ActionResult AddCategory([Bind(Prefix="NewCategory")]Category category)
{
...
return new开发者_StackOverflow中文版 Json(true);
}
Call Html.RenderAction to reuse action result in other views, and pass name parameter to it for your model, for example:
Use Html.RenderAction("AddCategory", new {name = Model.CategoryName})
The solution is to create another method with the "same" assignature:
[ActionName("AddCategory")]
public ActionResult AddCategory2([Bind(Prefix="NewCategory2")]Category category)
{
...
return new Json(true);
}
what i understand from your question is that you are in some View X and you want to render AddCategory View inside this view and Model of View X contains NewCategory which is of type Category and accepted by AddCategory View as model. if so you just have to call render partial in your View X
<%Html.RenderPartial("AddCategory", Model.NewCategory);%>
精彩评论