从视图返回的ASP.NET MVC bool值为1或0

时间:2014-10-04 00:09:54

标签: asp.net-mvc boolean model-binding checkboxfor

我使用的是ASP.NET MVC,使用CheckBoxFor时遇到了一些问题。这是我的问题:

我在视图中有以下代码:

@Html.CheckBoxFor(model => model.stade, new { @id = "stade" })

model.stade属于bool类型。在我的控制器中,我有:

//Editar
[HttpPost]
public ActionResult InvoiceType(int Id, string Name, string Code, string Stade)
{
    clsInvoiceTypea Model = new clsInvoiceType();
    Model.Id = Id;
    Model.Name = Name;
    Model.Code = Code;
    Model.Stade = stade== "1" ? true : false;
    return PartialView(Model);
}

我收到错误,因为当Model.Stade提交给视图时,值为1或0,我收到错误说"无法将字符串识别为有效的布尔值",但如果Model.stade是布尔值,为什么模型被提交到视图,如0或1?我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:2)

这是我的解决方案 -

让你的模型成为 -

public class clsInvoiceTypea
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public bool stade { get; set; }
    }

让你的HttpGet行动成为 -

public ActionResult GetInvoice()
{
    clsInvoiceTypea type = new clsInvoiceTypea();
    return View(type);
}

和相应的观点 -

@model YourValidNameSpace.clsInvoiceTypea

@{
    ViewBag.Title = "GetInvoice";
}

<h2>GetInvoice</h2>

@using (Html.BeginForm("SubmitData","Home",FormMethod.Post)) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>clsInvoiceTypea</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Code)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Code)
            @Html.ValidationMessageFor(model => model.Code)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.stade)
        </div>
        <div class="editor-field">
            @Html.CheckBoxFor(model => model.stade)
            @Html.ValidationMessageFor(model => model.stade)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

让以下内容成为你的HttpPost行动 -

[HttpPost]
public ActionResult SubmitData(clsInvoiceTypea model)
{
    return View();
}

运行代码时,您将获得以下视图 -

enter image description here

当您选中复选框并点击“创建”按钮时,如果您在POST方法上放置一个断点并检查该值,那么您将获得该值。

enter image description here