我有一些Html.ValidationSummary的问题.我不想在ValidationSummary中显示属性错误.当我设置Html.ValidationSummary(true)时,它不会显示来自ModelState的错误消息.在字符串的控制器操作中有一些异常时
MembersManager.RegisterMember(member);
Run Code Online (Sandbox Code Playgroud)
catch部分向ModelState添加错误:
ModelState.AddModelError("error", ex.Message);
Run Code Online (Sandbox Code Playgroud)
但ValidationSummary不显示此错误消息.当我设置Html.ValidationSummary(false)时,所有消息都显示,但我不想显示属性错误.我该如何解决这个问题?
这是我正在使用的代码:
模型:
public class Member
{
[Required(ErrorMessage = "*")]
[DisplayName("Login:")]
public string Login { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Password:")]
public string Password { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Confirm Password:")]
public string ConfirmPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[HttpPost]
public ActionResult Register(Member member)
{
try
{
if (!ModelState.IsValid)
return View();
MembersManager.RegisterMember(member);
}
catch (Exception ex)
{
ModelState.AddModelError("error", ex.Message);
return View(member);
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
<% using (Html.BeginForm("Register", "Members", FormMethod.Post, …Run Code Online (Sandbox Code Playgroud) 我在检查我的数据库Create(FooViewModel fvm){...},看是否fvm.prop1和fvm.prop2在该组合已经存在; 如果是这样,我想向modelstate添加一个错误,然后返回整个视图.我试过了:
public ActionResult Create(FooViewModel fvm){
if (ThatComboAlreadyExists(fvm)) {
ModelState.AddModelError("Model", "There is already one like that");
return View(fvm);
}
}
Run Code Online (Sandbox Code Playgroud)
...但我没有显示错误Html.ValidationSummary,这是我认为它们会出现的地方.我怀疑"模型"不是正确的关键,但我一直无法找到任何谷歌.
在我的Web应用程序中,我正在验证来自glabal.asax的URL.我想验证网址,如果需要,还需要重定向到某个操作.我正在使用Application_BeginRequest来捕获请求事件.
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
Run Code Online (Sandbox Code Playgroud)
或者是否有任何其他方法来验证每个URL,同时在mvc中获取请求并在需要时重定向到操作
asp.net-mvc asp.net-mvc-2-validation asp.net-mvc-3 asp.net-mvc-4 asp.net-mvc-5
有一种方法可以将默认资源设置为数据注释验证吗?
我不想做这样的事情:
[Required(ErrorMessage="Name required.", ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
Global.asax中
DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources);
Run Code Online (Sandbox Code Playgroud)
然后
[Required]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
有人给我一个光!
提前致谢
编辑
我真正的问题是使用EF Code First CTP4.CTP5修复它.谢谢大家.
.net asp.net-mvc-2-validation data-annotations asp.net-mvc-2
我有一个注册表单,我使用客户端验证(在我的视图模型上指定Required,StringLength等).表格目前几乎是脚手架创建它的方式:
@using (Html.BeginForm("Index", "Registration"))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Registration details</legend>
@Html.ValidationSummary(false, "Please correct these errors:")
@Html.ValidationMessageFor(model => model.Username)
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
Run Code Online (Sandbox Code Playgroud)
唯一的区别是我将ValidationMessageFor移动到ValidationSummary下面的右上角.
我想要做的是在验证摘要中显示客户端验证错误.目前,它们只显示在表单的顶部,但未使用验证摘要.如何使用验证摘要显示客户端验证错误?这甚至可能吗?
更新
Darin我在新项目中使用了你的代码,当客户端验证开始时,这就是我的样子:
客户端验证http://i56.tinypic.com/i3f320.jpg
我希望在验证摘要中显示这个,并应用验证摘要样式.我还提交了表格,然后看起来像这样:
提交http://i55.tinypic.com/2hqcowh.jpg后
谢谢,
B3N
asp.net-mvc validationsummary asp.net-mvc-2-validation asp.net-mvc-3
我有单独的模型和视图模型类.其中viewmodel类仅进行UI级别验证(请参阅:验证:模型或ViewModel).
我可以在控制器中验证模型(vewmodel)是否有效.
问:我如何验证模型(带有数据注释的主要实体).
我没有使用模型对象开发viewmodel.只需复制属性并添加该特定视图中可能需要的所有属性.
//Model Class
public class User
{
[Required]
public string Email {get; set;}
[Required]
public DateTime Created {get; set;}
}
//ViewModel Class
public class UserViewModel
{
[Required]
public string Email {get; set;}
[Required]
public string LivesIn {get; set;}
}
//Post action
public ActionResult(UserViewModel uvm)
{
if( ModelState.IsValid)
//means user entered data correctly and is validated
User u = new User() {Email = uvm.Email, Created = DateTime.Now};
//How do I validate "u"?
return View();
}
Run Code Online (Sandbox Code Playgroud)
应该做这样的事情: …
您建议在MVC中验证客户端的DateTime有哪些方法?
比方说,我有一个命名属性的模型DateOfBirth是一个DateTime,像这样.
public class UserModel
{
[DataType(DataType.Date)]
public DateTime DateOfBirth {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
在View上,我有一个简单的
<%: Html.LabelFor(model=>model.DateOfBirth) %>
<%: Html.EditorFor(model=>model.DateOfBirth) %>
<%: Html.ValidationMessageFor(model=>model.DateOfBirth) %>
<input type="submit" value="Submit" />
Run Code Online (Sandbox Code Playgroud)
我可以使用Microsoft MVC验证或jQuery验证.如何让DateTime验证客户端?
我意识到所有DataTypeAttribute都提供了格式化提示,并没有真正做任何验证(它将该部分留给了ModelBinder).
基本上我想复制ModelBinder在尝试将发布的值放入模型的DateOfBirth属性时所做的事情.
你有什么建议?
javascript datetime client-side-validation asp.net-mvc-2-validation asp.net-mvc-2
我有这个课程:
public class GroupMetadata
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
[MetadataType(typeof(GrupoMetadata))]
public partial class Group
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这个动作:
[HttpPost]
public ActionResult Edit(Group group)
{
if (ModelState.IsValid)
{
// Logic to save
return RedirectToAction("Index");
}
return View(group);
}
Run Code Online (Sandbox Code Playgroud)
这是我的观点:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Group>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% …Run Code Online (Sandbox Code Playgroud) 我有这样的模型:
public PurchaseOrder
{
[Required] [StringLength(15)]
public virtual string OrderNumber {get;set;}
// etc.
}
Run Code Online (Sandbox Code Playgroud)
当我从视图中提交订单时(使用$ .post,而不是输入type = submit),它会转到我的控制器类:
public class PurchaseOrderController
{
public JsonResult Save(PurchaseOrder order)
{
// TryUpdateModel(order); // commented out since modelstate.isvalid remains false anyway
if (ModelState.IsValid)
{
// its never valid
}
}
}
Run Code Online (Sandbox Code Playgroud)
ModelState.IsValid始终返回false,并返回错误:"订单号字段是必需的." 但是这个领域有一个价值(??为什么)
当它确实有价值时,为什么会说"价值是必需的"?我错过了什么吗?是因为$ .post而不是提交?我能做什么?
这是调试器的样子:
alt text http://www.freeimagehosting.net/uploads/f734f3d95d.png
编辑:额外信息....
我真的认为由于某种原因,模型绑定没有发生.当我尝试这里找到的代码:)
if (!ModelState.IsValid)
{
ModelState.Clear();
ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => order, order.GetType());
ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, base.ControllerContext);
foreach (ModelValidationResult result in compositeValidator.Validate(null))
{
this.ModelState.AddModelError(result.MemberName, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用System.ComponentModel.DataAnnotations属性验证包含具有验证规则的其他对象的模型,希望默认的MVC实现就足够了:
var obj = js.Deserialize(json, objectInfo.ObjectType);
if(!TryValidateModel(obj))
{
// Handle failed model validation.
}
Run Code Online (Sandbox Code Playgroud)
该对象由原始类型组成,但也包含其他也使用DataAnnotications的类.像这样:
public class Entry
{
[Required]
public Person Subscriber { get; set; }
[Required]
public String Company { get; set; }
}
public class Person
{
public String FirstName { get; set;}
[Required]
public String Surname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
问题是ASP.NET MVC验证只降低了1级,只评估顶级类的属性,可以在digitallycreated.net/Blog/54/deep-inside-asp.net-mvc-2上阅读-model-元数据和验证.
有谁知道这个优雅的解决方案?我尝试过xVal,但它们似乎使用了非递归模式(http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/).
有人必须在此之前遇到这个问题吗?如果您正在设计Web服务,那么在模型中嵌套对象似乎并不那么奇怪.
validation asp.net-mvc asp.net-mvc-2-validation data-annotations asp.net-mvc-2
asp.net-mvc ×5
c# ×2
modelstate ×2
.net ×1
datetime ×1
javascript ×1
model ×1
validation ×1
viewmodel ×1