开发者

How to keep state of typed viewmodel objects in partial views?

Hi,

I have a Strongly typed view in ASP.NET MVC. To keep track on properties of the model when thay are not connected to a field(ex TextBoxFor) I will have to use a HTML.HiddenFor element. This makes it easy to manipulate the data and get it back to the serv开发者_运维问答er.

Say now that my strongly typed view contains a partial view where I provide a bit of my model from the main view, like this :

<% Html.RenderPartial("~/Views/Ad/Partial/ListSettings.ascx", Model.ALS); %>

All the javascript for reading and manipulate the ALS proerpty(complexed object) is placed in the partial view to be abel to use the partial view on other main views.

In this partial view I have also the following lines :

<%: Html.HiddenFor(c => c.CP) %>
<%: Html.HiddenFor(c => c.L) %>
<%: Html.HiddenFor(c => c.OB) %>
<%: Html.HiddenFor(c => c.ST)%>
<%: Html.HiddenFor(c => c.P)%>

And this works fine to read by the javascript but when submitting the view the settings of these properties will not follow back to the service?

I did try to place them in the main view instead like this :

<%: Html.HiddenFor(c => c.ALS.CP) %>
<%: Html.HiddenFor(c => c.ALS.L) %>
<%: Html.HiddenFor(c => c.ALS.OB) %>
<%: Html.HiddenFor(c => c.ALS.ST)%>
<%: Html.HiddenFor(c => c.ALS.P)%>

And point the javascript to the correct fields but even if this works the problem is that the partial view will not caontain everything it needs, I will have to implement these hidden filed in every main view that the partial view is placed in?

How to handle this?

BestRegards


If all those fields are not going to be modifiable by the user you could simply include a hidden field containing some id that will allow you to fetch them back from the data source. For example:

<%= Html.HiddenFor(x => x.Id) %>

and now this id will be posted back to the controller if it is wrapped inside a form or could be used by javascript and sent along an AJAX request. Inside the controller action you would use the id and fetch everything from wherever it was initially stored:

[HttpPost]
public ActionResult Foo(int id)
{
    var model = _repository.Get(id);
    ...
}

If the properties are modifiable then you would use standard input elements such as textboxes and dropdownlists allowing for the user to set their values and then your POST controller action would take the updated view model as argument.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜