如何使字符串类型的模型属性在ASP.NET MVC复选框 [英] How to render a model property of string type as checkbox in ASP.NET MVC
问题描述
我要显示一个字符串类型作为MVC视图复选框,但返回它作为HTTP发布字符串类型。的问题是,它返回对HTTP POST错误的。下面是我的code:
I want to display a string type as checkbox on MVC view, but returns it as string type on HTTP post. The problem is that it returns false on HTTP Post. Below is my code:
查看:
@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);
}
任何理想的情况是非常多的AP preciated。
Any ideal would be very much appreciated.
推荐答案
您可以尝试在你的助手指定一个模板名称:
You can try specifying a template name in your helper:
@Html.EditorFor(car => car.IsFourWheel, "CheckBox")
和定义模板来呈现数据你想要的方式,在任何〜/查看/ {} YourControllerName /EditorTemplates/CheckBox.cshtml
或〜/查看/共享/ EditorTemplates / CheckBox.cshtml
。
And defining the template to render the data the way you want, in either ~/Views/{YourControllerName}/EditorTemplates/CheckBox.cshtml
or ~/Views/Shared/EditorTemplates/CheckBox.cshtml
.
您可以在这里找到MVC的模板全系列后由布拉德·威尔逊:
You can find a whole series of post by Brad Wilson on MVC templates here:
布拉德·威尔逊:ASP .NET MVC 2模板,第1部分:介绍
这是MVC 2,但大多数概念仍然适用于MVC 3,以及(除剃刀语法)。
It is for MVC 2, but most concepts still apply to MVC 3 as well (save for the Razor syntax).
更新:
其实你可能不需要这个自定义模板。尝试使用 @ Html.CheckBoxFor(车= GT; car.IsFourWheel)。
而不是
Actually you probably don't need a custom template for this. Try using @Html.CheckBoxFor(car => car.IsFourWheel)
instead.
更新2:
下降〜/查看/共享/ 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" })
然后从你的观点,把它像这样:
Then from your view, call it like so:
@Html.EditorFor(model => model.IsFourWheel, "IsFourWheel")
我测试了它,并结合工程GET和POST场景。
I tested it and binding works in both GET and POST scenarios.
这篇关于如何使字符串类型的模型属性在ASP.NET MVC复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!