在帖子上,下拉列表SelectList.SelectedValue为空
我的模型如下:
public class testCreateModel
{
    public string s1 { get; set; }
    public SelectList DL { get; set; }
    public testCreateModel()
    {
        Dictionary<string, string> items = new Dictionary<string, string>();
        items.Add("1", "Item 1");
        items.Add("2", "Item 2");
        DL = new SelectList(items, "Key", "Value");
    }
}
我发起的行动是:
    public ActionResult testCreate()
    {
        testCreateModel model = new testCreateModel();
        return View(model);
    }
我的剃刀视图(删除不相关的部分)是:
@model Tasks.Models.testCreateModel
@using (Html.BeginForm()) {
<fieldset>
    <legend>testCreateModel</legend>
    <div class="editor-label">
        @Html.LabelFor(model => model.s1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.s1)
    </div>
    <div class="editor-label">
        Select an item:
    </div>
    <div class="editor-field">
        @Html.DropDownList("dropdownlist", (SelectList)Model.DL)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}
回发行动是:
    public ActionResult testCreate(testCreateModel model, FormCollection collection)
    {
        if (ModelState.IsValid)
        {
            Console.WriteLine("SelectedValue: ",model.DL.SelectedValue);
            Console.WriteLine("FormCollection:", collection["dropdownlist"]);
            // update database here...
        }
        return View(model);
    }
回帖后,model.DL.SelectedValue为空。 (但是,所选项目可以从FormCollection获得,但除此之外)。 DL对象仍然适当填充,否则立即窗口输出如下:
model.DL
{System.Web.Mvc.SelectList}
    base {System.Web.Mvc.MultiSelectList}: {System.Web.Mvc.SelectList}
    SelectedValue: null
model.DL.Items
Count = 2
    [0]: {[1, Item 1]}
    [1]: {[2, Item 2]}
model.DL.SelectedValue
null
Q1:我怎样才能使用SelectedValue属性呢?
现在,如果在Razor视图中,我将Html SELECT标记的名称更改为DL(即与模型中的属性名称相同):
@Html.DropDownList("DL", (SelectList)Model.DL)
我得到一个例外:
No parameterless constructor defined for this object. 
Stack Trace: 
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199
System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult 
...
Q2:为什么?
谢谢。
MVC将仅返回POST中选定选项的值,因此您需要一个属性来包含返回的单个值。
作为一个很好的建议,尝试通过ViewBag设置SelectLists,这有助于保持ViewModel不受需要填充表单的数据的干扰。
所以你的例子可以这样解决:
public class testCreateModel
{
    public string s1 { get; set; }
    public int SelectedValue { get; set; }
}
并在你的视图中做到这一点:
@Html.DropDownList("SelectedValue", (SelectList)ViewBag.DL)
在GET操作中填充ViewBag.DL之前。
至于Q2,默认的ModelBinder要求所有绑定的类型都有一个默认的构造函数(以便ModelBinder可以创建它们)
答案已被选中,但看看我是如何做到的。 以下代码是我通常在填充下拉菜单时执行的操作。 这是非常简单的,我建议你用它作为建立你的下拉的基础。
在我的视图顶部,我指定了我的视图模型:
@model MyProject.ViewModels.MyViewModel
在我看来,我有一个下拉列表,显示用户可以从中选择的所有银行:
<table>
     <tr>
          <td><b>Bank:</b></td>
          <td>
               @Html.DropDownListFor(
                    x => x.BankId,
                    new SelectList(Model.Banks, "Id", "Name", Model.BankId),
                    "-- Select --"
               )
               @Html.ValidationMessageFor(x => x.BankId)
          </td>
     </tr>
</table>
我总是有一个视图的视图模型,我从来没有将一个域对象直接传递给视图。 在这种情况下,我的视图模型将包含将从数据库填充的银行列表:
public class MyViewModel
{
     // Other properties
     public int BankId { get; set; }
     public IEnumerable<Bank> Banks { get; set; }
}
我的银行域名模式:
public class Bank
{
     public int Id { get; set; }
     public string Name { get; set; }
}
然后在我的操作方法中,我创建了我的视图模型的一个实例,并从数据库中填充银行列表。 完成此操作后,我将视图模型返回到视图:
public ActionResult MyActionMethod()
{
     MyViewModel viewModel = new ViewModel
     {
          // Database call to get all the banks
          // GetAll returns a list of Bank objects
          Banks = bankService.GetAll()
     };
     return View(viewModel);
}
[HttpPost]
public ActionResult MyActionMethod(MyViewModel viewModel)
{
    // If you have selected an item then BankId would have a value in it
}
我希望这有帮助。
链接地址: http://www.djcxy.com/p/53955.html上一篇: On Post, a drop down list SelectList.SelectedValue is null
下一篇: What is the easiest way to initialize a std::vector with hardcoded elements?
