2014-10-04 81 views
0

我正在使用ASP.NET MVC,并且我在使用CheckBoxFor时遇到了一些问题。这里是我的问题:从视图返回的ASP.NET MVC布尔值是1或0

我在视图下面的代码:

@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?我该如何解决这个问题?

+2

而不是试图绑定到单独的属性,绑定模式,而不是'公共的ActionResult InvoiceType(clsInvoiceTypea模型)'。 – 2014-10-04 00:20:09

+4

这段代码不会编译(提示:'Stade'!='stade') – DavidG 2014-10-04 00:21:26

+0

对不起,那是因为我把代码翻译成英文,我说西班牙语 – Wilmer 2014-10-04 19:11:40

回答

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> 
} 

让以下b你e HttpPost行动 -

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

当您运行的代码,你会得到以下观点 -

enter image description here

当您选中该复选框,然后点击Create按钮,如果你把一个断点POST方法并检查值,你会得到真实的。

enter image description here

+0

谢谢,但问题是,当我从视图model.stade值发送到控制器收到1或0,当从控制器发送模型到视图是相同的,值是1或0,这会得到一个错误,因为model.state是布尔类型,不接受数字 – Wilmer 2014-10-04 19:35:53

+0

我不明白为什么布尔值被更改为一个数字? – Wilmer 2014-10-04 19:36:19

+0

@ user3303841,你能告诉我你的模型代码吗? – ramiramilu 2014-10-04 19:45:12