C# 为什么 ModelState.IsValid 在 mvc 中总是返回 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15333513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why ModelState.IsValid always return false in mvc
提问by Sraj Mane
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);
}
And my view code as below
我的视图代码如下
@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>
}
}
So please what is reason ModelState.IsValid
is return false in page post time ...
所以请问是什么原因ModelState.IsValid
是在页面发布时间返回false ...
采纳答案by Karthik Chintala
Please post your ModelClass.
请发布您的模型类。
To check the errors in your ModelState
use the following code:
要检查您ModelState
使用的错误,请使用以下代码:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
OR:You can also use
或:您也可以使用
var errors = ModelState.Values.SelectMany(v => v.Errors);
Place a break point at the above line and see what are the errors in your ModelState
.
在上面的行上放置一个断点,看看你的ModelState
.
回答by Shubh
As Brad Wilson states in his answer here:
正如布拉德威尔逊在他的回答中所说:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
ModelState.IsValid 会告诉您是否已将任何模型错误添加到 ModelState。
默认模型绑定器将为基本类型转换问题添加一些错误(例如,为“int”类型传递非数字)。您可以根据您使用的任何验证系统更全面地填充 ModelState。
Try using :-
尝试使用:-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy thisand this
回答by jishnu saha
"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.
“ModelState.IsValid”告诉您模型被视图(即 PaymentAdviceEntity)使用,是否满足所有类型的验证或未通过 DataAnotation 在模型属性中指定。
In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.
在这段代码中,视图没有绑定任何模型属性。因此,如果您在模型中放置任何 DataAnotations 或验证(即 PaymentAdviceEntity)。那么验证不满足。假设模型中的任何属性是名称,这使得模型中需要。然后发布后属性的值保持空白。因此模型无效(即 ModelState.IsValid 返回 false)。您需要删除模型级验证。