【问题标题】:Custom Model Binder for DropDownList not Selecting Correct ValueDropDownList 的自定义模型绑定器未选择正确的值
【发布时间】:2010-09-06 01:33:14
【问题描述】:

我创建了自己的自定义模型绑定器来处理我的视图中定义的 Section 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()));

    ...
}

这可以很好地验证,并且在更新模型时为该部分分配正确的值,但是如果另一个属性未验证,则它不会选择正确的值。

如果有人能告诉我如何做到这一点,我将不胜感激。谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc modelbinders model-binding custom-model-binder


    【解决方案1】:

    问题通过以下方式解决:

    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 是一个整数的情况下得到了解决。当您将其转换为字符串时,一切正常。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      相关资源
      最近更新 更多