开发者

How to pass parent model from inside partial view

I am rendering a parital view which has a submit button with HttpPost action in controller. This action method needs parent model as its parameter. Is there any way to send parent model as first parameter from inside a partial view?

Main view -> aspx file which has model as ParentModel

Partial view -> ascx file which has model as ParentModel.ChildModel

Controller action -> MyActionName(ParentModel model, int direction, int user)

If I keep the method as HttpPost then by default Parent model gets passed but then I cannot send 2nd and 3rd parameter as their values are decided at 开发者_高级运维run time and these are not childmodel properties. e.g. direction parameter which indicates if user has clicked next/prev button. In this case, next and prev buttons call same action method (MultipleAction submit)

Additional info: My parent model has a collection of child model. I am looping through this collection and calling RenderPartial for each item. So, I cannot pass this parent model directly to my partial view (which is default behavior).

Any suggestions please? Thanks..


You could wrap all those partials into a HTML <form> so that all values get submitted too the server when this form is posted:

<% using (Html.BeginForm()) { %>

    <%= Html.TextBoxFor(x => x.SomePropertyOfParent) %>
    <%= Html.TextBoxFor(x => x.SomeOtherPropertyOfParent) %>

    <%= Html.EditorFor(x => x.Children) %>

    <input type="submit" value="OK" />
<% } %>

I use an editor template instead of partials for the Children collection. The custom editor template will automatically be rendered for each element of this children collection and provide any input fields allowing to modify it.

Then when the form is finally submitted all the properties required by the model binder to reconstruct the ParentModel will be sent to the server. As far as the direction and user parameters are concerned I would make them part of the parent view model so that my POST controller action looks like this:

[HttpPost]
public ActionResult MyActionName(ParentViewModel model)
{
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜