简体   繁体   English

如何将字符串形式的选择列表传递给控制器​​,以在asp.net MVC 5中另存为int值

[英]How do I pass selectlist that is string to controller to save as a int value in asp.net mvc 5

I am trying to pass categorized value (string) into model that requires int value. 我试图将分类的值(字符串)传递到需要int值的模型中。

I have model AccountViewModel below: 我在下面有模型AccountViewModel

[Required]
[Display(Name = "Fleet Type")]
public int FleetType { get; set; }

When a user registers for the first time, they must choose the fleet type I have an AccountController : 用户首次注册时,必须选择我具有AccountController的车队类型:

public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var fleetType = 0;
        string fleetTypeStr = ViewBag.FleetType;

        switch (fleetTypeStr)
        {
            case "17' Truck":
                fleetType = 1;
                break;
            case "20' Truck":
                fleetType = 2;
                break;
            default:
                fleetType = 0;
                break;
        }

        var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            LoginId = model.LoginId,
            FirstName = model.FirstName,
            LastName = model.LastName,
            //FleetType = model.FleetType,
            FleetType = fleetType,
        };

In Account/Register view: 在“帐户/注册”视图中:

ViewBag.FleetTypeList = new SelectList(new List<string>
{
    "Pickup Truck", "Cargo Vans", "10' Truck", "15' Truck", "17' Truck",
    "20' Truck", "26' Truck"
}, "fleetTypeList");

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    // ........
    @Html.DropDownListFor(m => m.FleetType, ViewBag.FleetTypeList as SelectList, new { @class = "btn btn-primary btn-lg dropdown-toggle" })

But I get a error message because the ViewBag.FleetTypeList is list of strings but the datatype FleetType requires int inside the model. 但是我收到一条错误消息,因为ViewBag.FleetTypeList是字符串列表,但是数据类型FleetType在模型内部需要int。

Please help me! 请帮我!

You should not be reading the ViewBag value in your HttpPost action method. 您不应该在HttpPost操作方法中读取ViewBag值。

ViewBag is usually used to transfer some data from your GET action method to the view. ViewBag通常用于将一些数据从GET操作方法传输到视图。 You can use it to pass the list of items you want to build your dropdown. 您可以使用它传递要构建下拉列表的项目列表。

With your current code, the HTML helper will render a SELECT element with name attribute value "FleetType" and when you submit the form, the selected option's value attribute value (in your case the same as the text) will be posted as the value of this SELECT element. 使用当前代码,HTML帮助器将呈现一个名称属性值为“ FleetType”的SELECT元素,当您提交表单时,所选选项的value属性值(在您的情况下与文本相同)将作为此SELECT元素。 But since your FleetType property is of int type, model binder will not be able to bind that string value to the int property ! 但是,由于您的FleetType属性是int类型的,因此模型绑定程序将无法将该string值绑定到int属性!

A better solution is added after this. 此后添加了更好的解决方案。 Read further. 进一步阅读。

You should add a string type property to your view model and use that 您应该在视图模型中添加一个字符串类型属性,并使用它

public class RegisterViewModel 
{
   public string SelectedFleet { set;get;}
   // Your other properties
}

And in the view, use this property as the first param if the DropDownListFor helper method. 在视图中,如果使用DropDownListFor helper方法,则将此属性用作第一个参数。

@Html.DropDownListFor(m => m.SelectedFleet , 
        ViewBag.FleetTypeList as SelectList, 
        new { @class = "btn btn-primary btn-lg dropdown-toggle" })

Now in your httppost action method, read the SelectedFleet value and use it 现在,在您的httppost操作方法中,读取SelectedFleet值并使用它

var fleetType = 0;
var fleetTypeStr = model.SelectedFleet ;
switch (fleetTypeStr)
{

}

A Better Solution 更好的解决方案

But a better solution is to completely avoid the switch block. 但是更好的解决方案是完全避免使用开关块。 What if you set the option's value attribute to the corresponding int value ? 如果将选项的value属性设置为相应的int值怎么办?

So update your GET action method to have a list of SelectListItem in ViewBag.FleetTypeList 因此,更新您的GET操作方法以在ViewBag.FleetTypeList中具有SelectListItem列表。

ViewBag.FleetTypeList = new List<SelectListItem>{
  new SelectListItem { Text="17 Truck", Value="1"},
  new SelectListItem { Text="20 Truck", Value="2"},
  new SelectListItem { Text="Something else", Value="0"}
};

and in the view 并认为

@Html.DropDownListFor(m => m.FleetType, ViewBag.FleetTypeList as List<SelectListItem>
                , new { @class = "btn btn-primary btn-lg dropdown-toggle" })

Now the SELECT element will be rendered with name attribute "FleetType" and when you submit the form, the selected option's value (int) will be submitted. 现在,将使用名称属性“ FleetType”呈现SELECT元素,并且在提交表单时,将提交所选选项的值(int)。 You can avoid the switch block and simply use model.FleetType wherever needed. 您可以避免使用开关块,而只需在需要的地方使用model.FleetType即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM