primary keys in form for post-back?
I have an asp.NET mvc 3 with razor website. I have a web page that is displaying a list of data from a database in a form such as:
<input type="text" name="blah1" value="blah" />
<input type="text" name="blah2" value="blahblah" />
<input type="text" name="blah3" value="blahblah" />
Each row above is assoicated with a primary key. When the user hits submit and posts 开发者_如何学Pythonback the FormCollection to the controller.. how do I go about getting the primary keys of each blah? Do I add a hidden field for each row that contains the primary key of that row? If so, how do I know which blah it is associated with as the FormCollection is just a dictionary?
I would recommend you using a view model:
public class MyViewModel
{
public string Id { get; set; }
public string Text { get; set; }
}
and then in your controller action you would send a list of those models to the view:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = "1", Text = "blah" },
new MyViewModel { Id = "2", Text = "blahblah" },
new MyViewModel { Id = "3", Text = "blahblah" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// Here you will get a collection of id and text for each item
...
}
}
and the view you could use hidden fields for the id and a textbox for the value:
@model IEnumerable<MyViewModel>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<input type="submit" value="OK" />
}
and the corresponding editor template (~/Views/Shared/EditorTemplates/MyViewModel.cshtml
):
@model MyViewModel
@Html.HiddenFor(x => x.Id)
@Html.TextBoxFor(x => x.Text)
精彩评论