When using strongly typed viewmodels, is it possible to post back checkbox values not in the viewmodel?
I am fairly new to .net. I using strongly typed viewmodels. I have a general question: is it possible to add checkboxes (or buttons) to the view without ad开发者_运维技巧ding them to the viewmodel and access the value (checked or unchecked) in the controller action? If so, please explain how. Does the method have to be post? Thanks
You can always get your form data by using:
Request.Form["FieldName"]
Or add them as arguments to the postback Action method:
[HttpPost]
public ActionResult Edit(MyModel modelData, string extraField) {
But why not add them to your model, this will make it a lot easier if want the use to correct validation error.
I don't really understand what you mean by adding checkboxes to the view without adding them to the viewmodel but let me try to illustrate with some example:
Suppose that you have the following form:
<a href="#" id="add">Add checkbox</a>
@using (Html.BeginForm())
{
<div id="placeholder"></div>
<input type="submit" value="OK" />
}
<script type="text/javascript">
var index = 0;
$('#add').click(function () {
$('#placeholder').append(
$('<input/>', {
type: 'checkbox',
name: 'foo[' + index + ']',
value: 'true'
})
).append(
$('<input/>', {
type: 'hidden',
name: 'foo[' + index + ']',
value: 'false'
})
);
index++;
return false;
});
</script>
and a controller which would receive the form POST:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IEnumerable<bool> foo)
{
// When you submit the form this action will be invoked
// and you will get an list of boolean values corresponding
// to each checkbox state
return View();
}
}
精彩评论