为什么ModelState.IsValid在MVC中总是返回false [英] Why ModelState.IsValid always return false in mvc
本文介绍了为什么ModelState.IsValid在MVC中总是返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的控制器中,此代码:
In my controller this code:
[HttpPost]
public ActionResult Edit(Company company, FormCollection IsCostCenters)
{
if (ModelState.IsValid)
{
Company objNewCompany = new Company();
//oParty.CostCenters.Clear();
using (PaymentAdviceEntityContainer db1 = new PaymentAdviceEntityContainer())
{
objNewCompany = db1.Companies.Find(company.Id);
objNewCompany.CostCenters.Clear();
string[] temp = IsCostCenters["CostCenters"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in temp)
{
if (s != "false")
{
CostCenter oCostCenter = new CostCenter();
oCostCenter = db1.CostCenters.Find(Convert.ToInt32(s));
objNewCompany.CostCenters.Add(oCostCenter);
}
}
db1.SaveChanges();
}
db.Entry(company).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CreatedById = new SelectList(db.Employees, "Id", "FirstName", company.CreatedById);
return View(company);
}
我的查看代码如下
@using PaymentAdviceEntity;
@{
ViewBag.Title = "Edit";
List<CostCenter> clist = new List<CostCenter>();
clist = ((List<CostCenter>)ViewBag.CostCenters).ToList();
}
<div style="line-height: 22px; width: 100%;height :3%; float: left; ">
@{
foreach (var item in clist)
{
<div style="line-height: 22px; width: 28%; float: left;">
<span class="checkbox">@Html.CheckBox("CostCenters", item.IsChecked, new { @value = item.Id })</span>
<span>@Html.DisplayFor(modelItem => item.Name)</span>
</div>
}
}
所以请问ModelState.IsValid
在页面发布时间返回false的原因是什么...
So please what is reason ModelState.IsValid
is return false in page post time ...
推荐答案
请发布您的 Model 类.
要检查ModelState
中的错误,请使用以下代码:
To check the errors in your ModelState
use the following code:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
或:,您也可以使用
var errors = ModelState.Values.SelectMany(v => v.Errors);
在上面的行上放置一个断点,看看您的ModelState
中有什么错误.
Place a break point at the above line and see what are the errors in your ModelState
.
这篇关于为什么ModelState.IsValid在MVC中总是返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文