编辑页面节约时忽略必需属性 [英] Ignore Required attribute when saving on edit page

查看:145
本文介绍了编辑页面节约时忽略必需属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有有几个必填字段的模型类:

I have a model class that has a couple of required fields:

public class UserMetadata
{
   [Required(ErrorMessage = "Please enter a name.")]
   public string Name { get; set; }

   [Required(ErrorMessage = "Please enter a password.")]
   public string Password { get; set; }
}

在创建视图,如果我不给一个名称和/或密码,然后出现验证摘要错误。所有漂亮和好。对于编辑视图,我只显示名称字段 - 我不显示密码字段

On the create view, if I don't give a name and/or password, then the validation summary errors appears. All nice and good. For the edit view, I'm only displaying the 'Name' field - I don't to show the 'Password' field.

当我保存编辑页面上我的变化,验证摘要错误显示说我必须输入密码。

When I save my changes on the edit page, the validation summary error appears saying that I must enter a password.

如何控制密码字段的验证,因此,对于编辑视图,它不应该打扰它?或者,我会处理这个错误的方式?我还是想在名称字段验证在编辑视图中工作。

How can I control the validation of the password field, so that for the edit view, it should not bother with it? Or, am I approaching this the wrong way? I still want the 'Name' field validation to work on the edit view.

编辑:

有关我的MVC项目,我使用实体框架。因此,我有一个'UserMetadata类定义的,这样我可以在用户类(这是在EDMX文件)连接之类的东西[必需]'上的某些字段。

For my MVC project, I'm using Entity Framework. Thus, I have a 'UserMetadata' class defined so that I can attached things like '[Required]' onto certain fields on the 'User' class (which is in the EDMX file).

我还要解释一下,我使用的视图模型如'UserEditViewModel其中有连接到它的属性用户。所以,在我的岗位:

I should also explain that I'm using a view model eg 'UserEditViewModel' which has a property 'User' attached to it. So on my post:

[HttpPost]
public ActionResult Edit(UserEditViewModel inputViewModel)
{

    if(ModelState.IsValid) { inputViewModel.User blah.... }

}

键入思考这个问题的时候我冲了一下。你认为重要的其他任何遗漏的信息的话,请给我留言。

Think I rushed a bit when typing this question. Any other missing information you think is important, then please give me a shout.

干杯。
雅各

推荐答案

我结束了我的操作方法这样做的:

I ended up doing this in my action method:

ModelState.Remove("User.Password");

现在我的code运行正常,仅在名称字段,而这正是我想要的。

Now my code runs fine, only raising validation errors on the "Name" field, which is what I wanted..

这篇关于编辑页面节约时忽略必需属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆