MVC DropDownList模型绑定

时间:2019-01-28 20:00:22

标签: c# asp.net-core asp.net-core-mvc

我正在尝试获取自定义SelectList的值以传递给控制器​​。我的选择列表选项是从db表中填充的:

public class Priority
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

我的视图模型和模型如下:

public class RequestViewModel
{
    public Request Request { get; set; }
    public IEnumerable<Priority> Priorities { get; set; }
}


public class Request
{
    public Guid Id { get; set; }
    public Priority Priority { get; set; }
}

使用

Html.DropDownListFor(x => x.Request.Priority, new SelectList(Model.Priorities, "Id", "Name", Model.Request.Priority), new { @class = "custom-select" })

使用文本和值正确填充了DropdownList。

编辑后,控制器中下拉列表的值为空。

public IActionResult Edit(RequestViewModel viewModel)
{
    var priority = viewModel.Request.Priority; // this is null

}

是否必须为此实例创建自定义ModelBinder?默认模型构建器是否无法从传递的值中获得正确选择的“优先级”?

还有,最好的做法是使用ViewBag而不是viewmodel将选择列表之类的信息传递给视图吗?

1 个答案:

答案 0 :(得分:1)

ASP.NET MVC小提琴在这里https://dotnetfiddle.net/PIPf4Z。同时,我希望这能回答您的问题。

Controller / ViewModel

public class RequestViewModel
{
    public Guid SelectedGuid { get; set; }
    //Text=Name, Value=Guid
    public List<SelectListItem> Priorities { get; set; }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Tut144(RequestViewModel selected)
    {
        RequestViewModel requestViewModel = GetData();
        return View();
    }

    public ActionResult Tut144()
    {
        RequestViewModel requestViewModel = GetData();

        return View(requestViewModel);
    }

    private static RequestViewModel GetData()
    {
        //prep the vcontroller-you can do this from db
        List<SelectListItem> list = new List<SelectListItem>();
        SelectListItem selectListItemA = new SelectListItem { Text = "Priority1", Value = Guid.NewGuid().ToString() };
        SelectListItem selectListItemB = new SelectListItem { Text = "Priority2", Value = Guid.NewGuid().ToString() };
        SelectListItem selectListItemC = new SelectListItem { Text = "Priority3", Value = Guid.NewGuid().ToString() };
        list.Add(selectListItemA);
        list.Add(selectListItemB);
        list.Add(selectListItemC);
        RequestViewModel requestViewModel = new RequestViewModel { Priorities = list };
        return requestViewModel;
    }

查看

@model Testy20161006.Controllers.RequestViewModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Tut144</title>
</head>
<body>
    @using (Html.BeginForm())
    {
    <table>
        <tr>
            <td>Priority:</td>
            <td>
                @Html.DropDownListFor(m => m.SelectedGuid,
                         new SelectList(Model.Priorities, "Value", "Text"))
            </td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Go" /></td>
        </tr>
    </table>
    }
</body>
</html>