MVC 4验证了局部视图 [英] MVC 4 Validation with a partial view
问题描述
我使用MVC 4和实体框架,开发一个Web应用程序。我正与其中加载了JavaScript的部分景色。其中之一是创建视图,其中包括验证。这是我的问题:验证。我有一个自验证逻辑和,例如,如果用户输入一些数字成一个领域,如名称,它显示一个错误。
下面,用局部视图,它重定向我在我的部分,并显示错误,但我想要做的是留在我的主视图(索引视图),并保持它显示错误,我的局部视图。
编辑:
下面是我的部分观点:
@model BuSIMaterial.Models.Person
@using(Html.BeginForm()){
@ Html.ValidationSummary(真)
<字段集>
<传奇>人< /传说>
< DIV CLASS =编辑标记>
名字 :
< / DIV>
< DIV CLASS =主编场>
@ Html.TextBoxFor(型号=> model.FirstName,新{最大长度= 50})
@ Html.ValidationMessageFor(型号=> model.FirstName)
< / DIV>
< DIV CLASS =编辑标记>
姓 :
< / DIV>
< DIV CLASS =主编场>
@ Html.TextBoxFor(型号=> model.LastName,新{最大长度= 50})
@ Html.ValidationMessageFor(型号=> model.LastName)
< / DIV>
< DIV CLASS =编辑标记>
国家编号:
< / DIV>
< DIV CLASS =主编场>
@ Html.TextBoxFor(型号=> model.NumNat,新{最大长度= 11})
@ Html.ValidationMessageFor(型号=> model.NumNat)
< / DIV>
< DIV CLASS =编辑标记>
开始日期 :
< / DIV>
< DIV CLASS =主编场>
@ Html.TextBoxFor(型号=> model.StartDate,新{@class =日期选择器,@占位符=YYYY / MM / DD})
@ Html.ValidationMessageFor(型号=> model.StartDate)
< / DIV>
< DIV CLASS =编辑标记>
结束日期 :
< / DIV>
< DIV CLASS =主编场>
@ Html.TextBoxFor(型号=> model.EndDate,新{@class =日期选择器,@placeholder =YYYY / MM / DD})
@ Html.ValidationMessageFor(型号=> model.EndDate)
< / DIV>
< DIV CLASS =编辑标记>
距离之家 - 工作(公里):
< / DIV>
< DIV CLASS =主编场>
@ Html.EditorFor(型号=> model.HouseToWorkKilometers)
@ Html.ValidationMessageFor(型号=> model.HouseToWorkKilometers)
< / DIV>
< DIV CLASS =编辑标记>
类别 :
< / DIV>
< DIV CLASS =主编场>
@ Html.DropDownList(Id_ProductPackageCategory,选择...)
@ Html.ValidationMessageFor(型号=> model.Id_ProductPackageCategory)< A HREF =../ProductPackageCategory/Create">Add一个新的类别< / A>
< / DIV>
< DIV CLASS =编辑标记>
升级? :
< / DIV>
< DIV CLASS =主编场>
@ Html.EditorFor(型号=> model.Upgrade)
@ Html.ValidationMessageFor(型号=> model.Upgrade)
< / DIV>
< BR />
< DIV CLASS =表单行动>
<按钮类型=提交级=BTN BTN小学>创建< /按钮>
< / DIV>
< /字段集>
}
@section脚本{
@ Scripts.Render(〜/包/ jqueryval)
@ Scripts.Render(〜/包/ jQueryUI的)
@ Styles.Render(〜/内容/主题/基/ CSS)
}
在我看来指数,我有这样的:
< DIV CLASS =表单行动><按钮式=按钮ID =创造类=BTN BTN小学>创建< /按钮> < / DIV>
< DIV ID =create_person>< / DIV>
和我打开我的局部视图的方式:
$(#创建)。点击(函数(){
变种形式= $(#create_person)最近(形式)。
form.removeData('验证');
form.removeData('unobtrusiveValidation');
$ .validator.unobtrusive.parse(表);
$阿贾克斯({
网址:/人/ CreateOrUpdate
键入:POST,
数据:$(#create_person)序列化()。
缓存:假的
});
// VAR URL ='/人/ CreatePerson;
// $(#create_person)负载(URL)。
});
的行动:
[HTTPGET]
公众的ActionResult CreateOrUpdate()
{
ViewBag.Id_ProductPackageCategory =新的SelectList(db.ProductPackageCategories,Id_ProductPackageCategory,姓名);
返回查看();
}
[HttpPost]
公共JsonResult CreateOrUpdate(人人)
{
ViewBag.Id_ProductPackageCategory =新的SelectList(db.ProductPackageCategories,Id_ProductPackageCategory,姓名,person.Id_ProductPackageCategory);
尝试
{
如果(!ModelState.IsValid)
{
串消息的string.join =(;,ModelState.Values
.SelectMany(X => x.Errors)
。选择(X => x.ErrorMessage));
抛出新的异常(请更正以下错误:+ Environment.NewLine +消息);
}
db.Persons.AddObject(人);
db.SaveChanges();
返回JSON(新{结果=OK});
}
赶上(例外前)
{
返回JSON(新{结果=ERROR,消息= ex.Message});
}
}
如果您发布的网页就不会再来动态加载的局部视图。尝试拨打Ajax调用/人/ CreatePerson。您CreatePerson将类似于
[HttpPost]
公共JsonResult CreatePerson(人人)
{
ViewBag.Id_ProductPackageCategory =新的SelectList(db.ProductPackageCategories,Id_ProductPackageCategory,姓名,person.Id_ProductPackageCategory);
尝试
{
如果(!ModelState.IsValid)
{
串消息的string.join =(;,ModelState.Values
.SelectMany(X => x.Errors)
。选择(X => x.ErrorMessage));
抛出新的异常(请更正以下错误:+ Environment.NewLine +消息);
}
db.Persons.AddObject(人);
db.SaveChanges();
返回JSON(新{结果=OK});
}
赶上(例外前)
{
返回JSON(新{结果=ERROR,消息= ex.Message});
}
}`
在Ajax调用/人/ CreatePerson将类似于
`
$。阿贾克斯({
网址:/人/ CreatePerson',
键入:POST,
数据:$(#表)序列化()。
成功:函数(性反应){
警报(responce.Message);
},
错误:函数(XHR,textStatus){
警报(xhr.status ++ xhr.statusText);
}
});
除了不显眼的验证不会与动态内容轻松的工作。检查链接<一个href="http://stackoverflow.com/questions/9321040/unobtrusive-validation-on-dynamically-added-partial-view-not-working">unobtrusive验证在动态添加的局部视图(不工作)
I'm using MVC 4 and Entity Framework to develop a web app. I'm working with partial views which are loaded with javascript. One of them is a create view which includes validation. And that's my problem : the validation. I have a custom validation logic and, for example, if a user enters some numbers into a field such as "Name", it displays an error.
Here, with the partial views, it redirects me on my partial with the errors displayed but what I wanted to do is to stay on my main view (Index view) and keep my partial view which displays the errors.
EDIT :
Here is my partial view :
@model BuSIMaterial.Models.Person
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
First name :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
Last name :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
National number :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.NumNat, new { maxlength = 11 })
@Html.ValidationMessageFor(model => model.NumNat)
</div>
<div class="editor-label">
Start date :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.StartDate, new {@class = "datepicker", @placeholder="yyyy/mm/dd"})
@Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
End date :
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", @placeholder = "yyyy/mm/dd" })
@Html.ValidationMessageFor(model => model.EndDate)
</div>
<div class="editor-label">
Distance House - Work (km) :
</div>
<div class="editor-field">
@Html.EditorFor(model => model.HouseToWorkKilometers)
@Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
@Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
@Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) <a href = "../ProductPackageCategory/Create">Add a new category?</a>
</div>
<div class="editor-label">
Upgrade? :
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Upgrade)
@Html.ValidationMessageFor(model => model.Upgrade)
</div>
<br />
<div class="form-actions">
<button type="submit" class="btn btn-primary">Create</button>
</div>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css")
}
In my view Index, I have this :
<div class="form-actions"><button type="button" id="create" class="btn btn-primary">Create</button> </div>
<div id ="create_person"></div>
And the way I load my Partial View :
$("#create").click(function () {
var form = $("#create_person").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$.ajax({
url: "/Person/CreateOrUpdate",
type: "POST",
data: $("#create_person").serialize(),
cache: false
});
// var url = '/Person/CreatePerson';
// $("#create_person").load(url);
});
The actions :
[HttpGet]
public ActionResult CreateOrUpdate()
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name");
return View();
}
[HttpPost]
public JsonResult CreateOrUpdate(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
If you post the page it will not come back to the dynamically loaded partial view. Try to make a ajax call to /Person/CreatePerson. Your CreatePerson will look similar to
[HttpPost]
public JsonResult CreatePerson(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
} `
The ajax call to /Person/CreatePerson will look similar to
`
$.ajax({
url: '/Person/CreatePerson',
type: "POST",
data: $("#form").serialize(),
success: function (responce) {
alert(responce.Message);
},
error: function (xhr, textStatus) {
alert(xhr.status + " " + xhr.statusText);
}
});
Besides unobtrusive validation will not work easily with dynamic content. check the link unobtrusive validation on dynamically added partial view (not working)
这篇关于MVC 4验证了局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!