如何在ASP.NET MVC中将字符串类型的模型属性呈现为复选框

时间:2011-08-26 10:49:08

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我想在MVC视图上显示字符串类型作为复选框,但在HTTP帖子上将其作为字符串类型返回。问题是它在HTTP Post上返回false。以下是我的代码:

查看:

  @model List<Car>

        foreach(var car in Model){
       bool isFourWheel = false;
        if(bool.TryParse(car.IsFourWheel, out isFourWheel){
        @Html.CheckBox("IsFourWheel", isFourWheel); //need to be rendered as checkbox, but returns string type on HTTP POST
    }
     }

型号:

public class Car
    {
        public string IsFourWheel { get; set; } //bad naming, but it can contain any type, include boolean
    }

控制器:

 public ActionResult Index()
        {


            var cars = new List<Car>(){ new Car(){IsFourWheel = "true"},new Car(){IsFourWheel = "false"} };
            return View(cars);
        }

        [HttpPost]
        public ActionResult Index(List<Car> cars)  **Problem IsFourWheel is false when true is selected **
        {           
            return View(cars);
        }

非常感谢任何理想。

3 个答案:

答案 0 :(得分:5)

您可以尝试在帮助程序中指定模板名称:

@Html.EditorFor(car => car.IsFourWheel, "CheckBox")

~/Views/{YourControllerName}/EditorTemplates/CheckBox.cshtml~/Views/Shared/EditorTemplates/CheckBox.cshtml中定义模板以按照您希望的方式呈现数据。

你可以在MVC模板上找到Brad Wilson的一系列帖子:

Brad Wilson: ASP.NET MVC 2 Templates, Part 1: Introduction

适用于MVC 2,但大多数概念仍然适用于MVC 3(除了Razor语法)。

<强>更新

实际上你可能不需要自定义模板。请尝试使用@Html.CheckBoxFor(car => car.IsFourWheel)代替。

更新2:

~/Views/Shared/EditorTemplates中删除以下模板:

<强> IsFourWheel.cshtml

@functions {
    private bool IsChecked() {
        if (ViewData.Model == null) return false;
        return Convert.ToBoolean(ViewData.Model, System.Globalization.CultureInfo.InvariantCulture);
    }
}

@Html.CheckBox("", IsChecked(), new { @class = "check-box" })

然后从您的角度来看,请这样称呼:

@Html.EditorFor(model => model.IsFourWheel, "IsFourWheel")

我测试了它,绑定在GET和POST场景中都有效。

答案 1 :(得分:1)

您可以像这样更改您的viewmodel:

public class Car
    {
        public string IsFourWheel { get; set; }
        public bool IsFourWheelBool { get { return bool.Parse(IsFourWheel); } }
    }

您的观点如下所示:

@Html.EditFor(x => x.IsFourWheelBool);

答案 2 :(得分:1)

如果您在模型中添加ID,我认为会更容易。像这样
型号:

public class Car
{
    public int CarID { get; set; }
    public string IsFourWheel { get; set; }        
}


检视:

@model IEnumerable<Car>
foreach (var car in Model)
{
    if(car.IsFourWheel == "true"){
        <input type="checkbox" name="carID" value="@car.CarID" checked="checked" />
    }
    else
    {
        <input type="checkbox" name="carID" value="@car.CarID" />
    }
}

控制器:

[HttpPost]
public ActionResult Index(List<int> carID)
{
    //handle selected cars here
    return View();
}