Getting the strongly typed HTML helper value into a simple parameter type
I have an ActionMethod and I'm trying to bind a string from a value supplied by a strongly typed HTML helper:
public class SampleController : Controller
{
public ActionResult Save(string name)
{
return Content(name);
}
}
My view contains complex objects... and I'm trying to use strongly typed helpers as such:
@model MvcApplication2.Models.Sample
@using(Html.BeginForm("save", "sample")) {
@Html.TextBoxFor(x =>x.Product.Name)
<input type="submit" />
}
I know that the TextBox renders with the name Product.Name
<input id="Product_Name" name="Product.Name" type="text" value="">
and that I can bind to a complex Product
type with the name product
:
public ActionResult Save(Product product)
{
return Content(product.Name);
}
or use the Bind attribute to bind to a property with a different name:
public ActionResult Save([Bind(Prefix="Product")]Product p)
{
return Content(p.Name);
}
but how do I get it to bind to just a string value?
public ActionResult Save(string name)
{
return Content(name);
}
Thanks, Brian
Use the full prefix (the value of the name attribute) of the input field. For example:
public ActionResult Save([Bind(Prefix="Product.Name")]string name)
{
return Content(name);
}
If you desire even more control you can always use a custom model binder:
public class CustomModelBinder : IModelBinder
{
// insert implementation
}
public ActionResult Save([ModelBinder(typeof(CustomProductModelBinder))]string name){
// ...
}
链接地址: http://www.djcxy.com/p/19082.html