Post html select 到 MVC 控制器。寻找更好的方法

Post html select to MVC Controller. Finding a better way

我只是在寻找一种更好的方法来执行以下操作:

我有一个 html select :

<form method="post" action="/Account/ChangeUserRole">
  <select name="Val" onchange="this.form.submit();" class="span2">
   @foreach (var r in ViewBag.UserRoles)
   {
    @if (u.UserRole.ID == r.ID)
   {
    <option selected="selected" value="@u.ID/@r.ID">@r.Name</option>
   }
   else
   {
    <option value="@u.ID/@r.ID">@r.Name</option> // <-- better way?
   }
  }
  </select>
  </form>

我 post 将其设置为 "userid/roleid" 并在控制器端执行 string.Split on / 拆分 u.ID 和 r.ID

我想知道是否可以 post 以便我的控制器以这种方式获取它们 :

[HttpPost]
public IActionResult ChangeUserRole(int UserID, int RoleID)

而不是这个巫术:

[HttpPost]
public IActionResult ChangeUserRole(string Val)
{
    char[] splitChar = new char[] { '/' };
    string[] s = Val.Split(splitChar);
    int UserID = Convert.ToInt32(s[0]);
    int RoleID = Convert.ToInt32(s[1]);
}

抱歉这么久 post。希望我的问题有意义。 我不太喜欢 html 助手。

旁注: 我正在使用 MVC 6,ASP 5 - RC1

感谢帮助

干杯!

最好的解决方案是使用 TagHelpers 来构建您的下拉菜单。让我们从创建特定于此视图的视图模型开始。

public class UserRoleEditVm
{
    public List<SelectListItem> Roles { set; get; }
    public int RoleId { set; get; }
    public int UserId { set; get; }
}

在您的 get 操作中,为此创建一个对象,加载 属性 值并将其发送到视图。

public IActionResult Create()
{
   // User Id and Role list is hard coded for demo. You may replace it with real data.

    var v = new UserRoleEditVm {UserId = 45};
    v.Roles = new List<SelectListItem>
    {
        new SelectListItem {Value = "1", Text = "Admin"},
        new SelectListItem {Value = "2", Text = "Editor"},
        new SelectListItem {Value = "3", Text = "Reader"}
    };
    return View(v);
}

在您的视图中,我们的视图模型是强类型的,我们希望标签助手能够创建 HTML 标记。

@model UserRoleEditVm    
<form asp-action="ChangeUserRole" asp-controller="Account">

    <select asp-for="RoleId" asp-items="@Model.Roles">
        <option>Please select one role</option>
    </select>
    <input  type="hidden"asp-for="UserId"/>
    <input type="submit"/>

</form>

并且在您的 HttpPost 操作方法中,您可以使用我们视图模型的对象作为参数,模型绑定器会将发布的表单值映射到该对象的 属性 值。

[HttpPost]
public ActionResult ChangeUserRole(UserRoleEditVm model)
{
    var userId = model.UserId;
    var roleId = model.RoleId;
    // to do : Do something with the above 2 values
    // to do :Save and redirect (PRG pattern)
    // return RedirectToAction("Success");
}