Ana*_*tic 2 c# asp.net-mvc modelstate asp.net-mvc-5
我正在研究MVC5 Code-First应用程序.
在一个型号的Edit()观点我已经包括[Create]按钮,新的价值观从内部添加到其他模型Edit()视图,然后重新填充内的新值DropDownFors()上Edit().
对于第一次尝试,我将model_description通过AJAX 传递给我的控制器方法createNewModel():
[HttpPost]
public JsonResult createNewModel(INV_Models model)
{
// model.model_description is passed in via AJAX -- Ex. 411
model.created_date = DateTime.Now;
model.created_by = System.Environment.UserName;
model.modified_date = DateTime.Now;
model.modified_by = System.Environment.UserName;
// Set ID
int lastModelId = db.INV_Models.Max(mdl => mdl.Id);
model.Id = lastModelId+1;
//if (ModelState.IsValid == false && model.Id > 0)
//{
// ModelState.Clear();
//}
// Attempt to RE-Validate [model], still comes back "Invalid"
TryValidateModel(model);
// Store all errors relating to the ModelState.
var allErrors = ModelState.Values.SelectMany(x => x.Errors);
// I set a watch on [allErrors] and by drilling down into
// [allErrors]=>[Results View]=>[0]=>[ErrorMessage] I get
// "The created_by filed is required", which I'm setting....?
try
{
if (ModelState.IsValid)
{
db.INV_Models.Add(model);
db.SaveChangesAsync();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(
new { ID = model.Id, Text = model.model_description },
JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么我ModelState的出现Invalid?
在ModelState检查之前指定所有属性; 模型定义如下:
public class INV_Models
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a Model Description.")]
public string model_description { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime modified_date { get; set; }
public string modified_by { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编辑:
添加了查看代码:
输入表格:
<span class="control-label col-md-2">Type:</span>
<div class="col-md-4">
@Html.DropDownListFor(model => model.Type_Id, (SelectList)ViewBag.Model_List, "<<< CREATE NEW >>>", htmlAttributes: new { @class = "form-control dropdown" })
@Html.ValidationMessageFor(model => model.Type_Id, "", new { @class = "text-danger" })
</div>
<div class="col-md-1">
<div class="btn-group">
<button type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
脚本:
$('#submitNewModel').click(function () {
var form = $(this).closest('form');
var data = { model_description: document.getElementById('textNewModel').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '@Url.Action("createNewModel", "INV_Assets")',
data: data,
success: function (resp) {
alert("SUCCESS!");
$('#selectModel').append($('<option></option>').val(resp.ID).text(resp.Text));
alert("ID: " + resp.ID + " // New Model: " + resp.Text); // RETURNING 'undefined'...?
form[0].reset();
$('#createModelFormContainer').hide();
},
error: function () {
alert("ERROR!");
}
});
});
Run Code Online (Sandbox Code Playgroud)
当您无法快速推断出ModelState验证失败的原因时,快速迭代错误通常很有帮助.
foreach (ModelState state in ModelState.Values.Where(x => x.Errors.Count > 0)) { }
Run Code Online (Sandbox Code Playgroud)
或者,您可以直接提取错误.
var allErrors = ModelState.Values.SelectMany(x => x.Errors);
Run Code Online (Sandbox Code Playgroud)
请记住,ModelState是在Action的主体执行之前构造的.因此,无论您何时在Controller Action中设置模型的属性,都将设置IsValid.
如果您希望灵活地手动设置属性然后重新评估对象的有效性,则可以在设置属性后手动重新运行Action内部的验证.如评论中所述,您应该在尝试重新验证之前清除ModelState.
ModelState.Clear();
ValidateModel(model);
try
{
if (ModelState.IsValid)
{
db.INV_Models.Add(model);
db.SaveChangesAsync();
}
}
...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果模型仍然无效,ValidateModel(model)将抛出异常.如果您想阻止它,请使用TryValidateMode l,它返回true/false:
protected internal bool TryValidateModel(Object model)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11984 次 |
| 最近记录: |