Skip to main content
 首页 » 编程设计

c#之ASP.NET mvc4 DropDownListFor 传回一个对象

2024年02月13日16linjiqin

有没有办法告诉 DropDownListFor 回发一个对象而不是一个 Id?我有以下代码:

public class Foo 
{ 
    public int SelectedProductId { get; set; } 
 
    public decimal MonthlyIncome { get; set; } 
 
    public IEnumerable<Product> Products { get; set; } 
} 
 
@using(Html.BeginForm()) 
{ 
    @Html.DropDownListFor(x => x.SelectedProductId, new SelectList(Model.Products, "Id", "Name")) 
    <input type="submit" value="Submit"/> 
} 

这很好用。但在我的模型中,我想要 SelectedProduct 而不是 SelectedProductId。是否可以告诉 MVC 传回一个对象实例而不是它的 id?

谢谢。

请您参考如下方法:

是的,当然,首先您需要确保 SelectedProduct 具有 Id 和 Name 属性,然后您必须使 Model.Products 返回一个 SelectedProduct 列表并覆盖 SelectedProduct 上的几个方法,如下所示:

    public override bool Equals(object obj) 
    { 
        var other = obj as ClientLookup; 
        if (other == null) 
            return false; 
 
        return Id.Equals(other.Id); 
    } 
 
    public override int GetHashCode() 
    { 
        return Id.GetHashCode(); 
    } 
 
    public override string ToString() 
    { 
        return Id.ToString(); 
    } 

通过重写这些方法,尤其是 ToString,您可以确保内部 DropDownListFor 将您的 Model.Products 中的 SelectedProduct 与 Foo 中的当前 SelectedProduct 相匹配。

最后一部分是 ModelBinder,通过这种机制,您可以将 http 参数转换为要在目标模型中设置的对象,对于 SelectedProduct,您必须这样做:

public class SelectedProductModelBinder : IModelBinder 
{ 
 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
 
        SelectedProduct selectedProduct = new SelectedProduct(); 
        if (value.AttemptedValue != null && ! "".Equals(value.AttemptedValue)) 
            selectedProduct.Id = (int)value.ConvertTo(typeof(int)); 
        else 
            selectedProduct.Id = null; 
 
        return selectedProduct; 
    } 
} 

现在不要忘记在应用程序初始化期间注册 ModelBinder:

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
        AreaRegistration.RegisterAllAreas(); 
 
        WebApiConfig.Register(GlobalConfiguration.Configuration); 
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
        RouteConfig.RegisterRoutes(RouteTable.Routes); 
        BundleConfig.RegisterBundles(BundleTable.Bundles); 
 
        ModelBinders.Binders.Add(typeof(SelectedProduct), new SelectedProductModelBinder()); 
    } 
} 

希望这对您有所帮助。