MVC passing data from view to cotroller
I have little problem here with passing data from view to controller. This is a little CRUD site, here's some code to explain my poblem.
Model:
public class TempModel{
public List<Temp> Temp1 { get; set; }
}
View:
@{ using (Html.BeginForm()) {
for (int i = 0; i < TempModel.Temp1.Count; i++)
{
@Html.LabelFor(model => model.Temp[i].ModifiedBy, "Modified By: ")
@Html.TextBoxFor(model => model.Temp[i].ModifiedBy)
<button name="button" value="update">Update</button>
}
}
Controller:
[HttpPost]
public ActionResult Index(TempModel.Temp1, string button){
switch (button)
{
case "delete":
break;
case "update":
Upda开发者_开发技巧teSingleTemp(TempModel.Temp1);
break;
}
}
Now what I want to do is to pass which one of those Temp1[i] objects was changed when user press update. There must be simple way to tell controller ItemId or dataIsChanged or something like that but I just can't figure it out now. I'm pretty new with MVC.
EDIT: I managed to solve this problem.. The simplest way was just to use multiple forms and remove List from the model.
@for (int i = 0; i < TempModel.Count; i++)
@{ using (Html.BeginForm()) {
{
@Html.LabelFor(model => model[i].ModifiedBy, "Modified By: ")
@Html.TextBoxFor(model => model[i].ModifiedBy)
<button name="button" value="update">Update</button>
}
}
It is not possible directly. To track which field is updated or not, you have to store hash of each field and upon post back, compare the hash with the hash of submitted value, just like WebForms store ViewState in pages. Based on which field updated, you can trigger update method on the basic of updated fields.
For simplicity, you could use the Html Input Disabled Attribute. Disabled fields are not posted to server, so all of items controller gets, is tried to be updated by user. But, beware of using this with sensitive information, as web server should not trust user supplied values - user could simply enable all fields and post them. This method is useful in case you want to know which values user tried to edit and overwriting repository with new values will not cause problems. With sensitive information, change-checking should be done on server side as @Adeel adviced. For the first time, render all inputs with disabled attribute, then provide each editable field with additional button to enable them. For rendering with disabled attribute, use This Overload
精彩评论