代码之家  ›  专栏  ›  技术社区  ›  nfplee

DropDownList的自定义模型绑定器未选择正确的值

  •  1
  • nfplee  · 技术社区  · 14 年前

    我已经创建了自己的自定义模型绑定器来处理视图中定义的节DropDownList,如下所示:

    Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")
    

    这是我的活页夹模型:

    public class SectionModelBinder : DefaultModelBinder 
    { 
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
        { 
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
    
            if (bindingContext.ModelType.IsAssignableFrom(typeof(Section)) && value != null) 
            { 
                if (Utilities.IsInteger(value.AttemptedValue)) 
                    return Section.GetById(Convert.ToInt32(value.AttemptedValue)); 
                else if (value.AttemptedValue == "")
                    return null; 
            } 
    
            return base.BindModel(controllerContext, bindingContext); 
        } 
    }
    

    现在在我的控制器里我可以说:

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        var category = new Category();
    
        if (!TryUpdateModel(category, "Category")
            return View(new CategoryForm(category, _sectionRepository().GetAll()));
    
        ...
    }
    

    这可以很好地进行验证,并且在更新模型时为节指定正确的值,但是如果另一个属性没有验证,则不会选择正确的值。

    1 回复  |  直到 14 年前
        1
  •  0
  •   nfplee    14 年前

    解决问题的方法是:

    Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text"), "-- Please Select --") 
    

    这个问题似乎解决了SectionID是整数的问题。当你把它转换成一个字符串时,一切正常。希望这有帮助。