在ASP.NET MVC3中使用远程属性时,我遇到了意外情况.
我使用的模型类型:
using System;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace dTweets.Models
{
// at first time, user should create his account with unique username
// as in twitter.com, user do
public class UserMetadata
{
[HiddenInput]
internal int Identity { get; set; }
[Remote("IsUserExist", "Account")] // at any HttpPost, username should
// be unique – not appropriate if
// updating/editing this model later
[Required(ErrorMessage = "username should be unique")]
public string UserName { get; set; } // user cannot change it, later
[DataType(DataType.Password)]
public string Password { get; set; } // user can also change password, later
[DataType(DataType.MultilineText)]
public string About { get; set; } // Optional field – user can edit it later
}
[MetadataType(typeof(UserMetadata))]
[Bind(Include="UserName, Password, About")]
public partial class User
{
}
}
Run Code Online (Sandbox Code Playgroud)
远程属性在帐户创建时验证用户唯一名称.但是当后来的用户想要更新/更改他的帐户时,如果保持用户唯一名称相同,则Remote属性不允许更新模型.
这不是合适的结果,因为很少用户更改其唯一的用户名.他们只是更改其他字段,如关于字段或密码等.
[ 注意:在帐户创建时,我想检查用户唯一名称,所以我在这里使用了Remote属性,但是在以后更新用户帐户时我不再需要Remote属性]
我必须删除Remote属性以便稍后更新此模型.
我想更新/更改此模型而不更改用户唯一名称(远程属性应用于此唯一名称).
一种方法是在AdditionalFields命名参数中发送此记录的ID值
[Remote("IsUserExist", "Account",AdditionalFields = "Identity")]
Run Code Online (Sandbox Code Playgroud)
然后您可以检查除属于当前用户的行之外的所有行的唯一性.并且不要忘记更改IsUserEsists操作结果的签名以接收身份
public ActionResutl IsUserExists(string UserName, int Identity)
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1302 次 |
| 最近记录: |