@ Html.ValidationFor()一个@ Html.EditorFor(x => x.Name,typeof(string).FullName)

时间:2016-10-12 16:13:50

标签: c# html asp.net-mvc validation

提前感谢您的帮助。

我有一个摇摇欲坠的旧MVC客户端作为我的VS解决方案的一部分,我们称之为ApiClient(后端客户端)。根模型,我们称之为用户,具有所有验证要求和消息。但是,看看相关视图中的代码......

查看

@using Cms.Utils
@using Utils.Strings
@using Utils.Web
@using Utils.DateTimes
@using System.Web.Mvc
@using Models
@model Cms.Models.Users.AddModel

@SectionBreadcrumb.Add(Html, "Manage Users", "Add")
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<div class="col-xs-12">
    <div class="row">
        <h2>
            Add Person
        </h2>
    </div>
    <form method="POST">
            <div class="row">
                @*@Html.LabelFor(x => x.User.Username, new { @class = "control-label col-md-2" })*@
                <div>
                    @Html.EditorFor(x => x.User.Username, typeof(string).FullName, new { @class = "form-control" })
                </div>
                <div class="row">
                    @Html.ValidationMessageFor(x => x.User.Username, "", new { @class = "text-danger" })
                </div>
            </div>

查看模型

namespace Cms.Models.Users
{
    public class AddModel
    {
        public User User { get; set; }
        public List<Role> Roles { get; set; }
    }
}

这里我必须提到User是解决方案中Submodule(另一个项目)中的模型。它还继承自CoreUser(也在同一子模块中)

用户模型

namespace Models
{
    public class User : CoreUser
    {
        public bool IsFollowing { get; set; }
        public bool IsFollowingMe { get; set; }
    }
}

CoreUser模型

namespace Sqor.Models
{
    public class CoreUser : IEntity, IAttributeContainer
    {
        public int Id { get; set; }
        [StringLength(256), RegularExpression(@"[^\s@]+@[^\s@]+\.[^\s@]+", ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool IsPhoneVerified { get; set; }
        [StringLength(20, ErrorMessage = "Usernames cannot exceed 20 characters."), RegularExpression("^[a-zA-Z](_[a-zA-Z0-9]|[a-zA-Z0-9])+$", ErrorMessage = "Letters, numbers, and underscores only. Start with a letter. No spaces. Max length of 20 characters.")]
        public string Username { get; set; }
        [MaxLength(200, ErrorMessage = "Snippet cannot exceed 200 characters.")]
        public string Snippet { get; set; }
        [MaxLength]
        public string Bio { get; set; }
        public bool IsTeam { get; set; }
        public bool IsAmbassador { get; set; }
        public DateTime Created { get; set; }
        public string TimeZone { get; set; }
        public int? ContractTypeId { get; set; }
        public bool IsMvp { get; set; }
        public string FacebookPageId { get; set; }
        public string TwitterHandle { get; set; }
        public string WikipediaUrl { get; set; }
        public int NumberOfPosts { get; set; }
        public string College { get; set; }
        public bool? AdFree { get; set; }
        public bool MarketingEmails { get; set; }

        [StringLength(45, ErrorMessage = "First names cannot exceed 45 characters.")]
        [Obsolete("Use FirstName property instead.")]
        public string Firstname { get; set; }
        [StringLength(45, ErrorMessage = "Last names cannot exceed 45 characters.")]
        [Obsolete("Use LastName property instead.")]
        public string Lastname { get; set; }

        /// <summary>
        /// Use this property moving forward.
        /// </summary>
        /// 
        [StringLength(45, ErrorMessage = "First names cannot exceed 45 characters.")]
        public string FirstName
        {
#pragma warning disable 618
            get { return this.Firstname; }
            set { this.Firstname = value; }
#pragma warning restore 618
        }
        /// <summary>
        /// Use this property moving forward.
        /// </summary>
        /// 
        [StringLength(45, ErrorMessage = "Last names cannot exceed 45 characters.")]
        public string LastName
        {
#pragma warning disable 618
            get { return this.Lastname; }
            set { this.Lastname = value; }
#pragma warning restore 618
        }

        [RegularExpression(@"^([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(\s([0-1]\d|[2][0-3])(\:[0-5]\d){1,2})?$", ErrorMessage = "Please use a valid date. MM/DD/YYYY")]
        public DateTime? BirthDate { get; set; }
        [StringLength(45, ErrorMessage = "Locations cannot exceed 45 characters.")]
        public string Location { get; set; }
        [StringLength(45, ErrorMessage = "Gender cannot exceed 45 characters.")]
        public string Gender { get; set; }
        public string Avatar { get; set; }
        public string ProfileHeader { get; set; }
        public bool IsPlayer { get; set; }
        public bool IsUser { get; set; }

        public List<PlayerLeague> Leagues { get; set; }

        public List<AthleteContract> Contracts { get; set; }

        public List<Organization> Organizations { get; set; }

        public int? AccountManagerId { get; set; }

        [JsonIgnore]
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }

        EntityType IEntity.Type
        {
            get { return EntityType.User; }
        }

        string IEntity.Name
        {
            get { return FullName; }
        }

        string IEntity.Team
        {
            get { return null; }
        }

        string IEntity.League
        {
            get { return null; }
        }

        int IEntity.LeaguePrecedence
        {
            get { return 0; }
        }

        string IEntity.JerseyNumber
        {
            get { return null; }
        }

        string IEntity.Position
        {
            get { return null; }
        }


        [JsonIgnore]
        public Dictionary<string, object> Attributes
        {
            get { return AttributeTokens != null ? AttributeTokens.ToDictionary(x => x.Key, x => x.Value == null ? null : x.Value.ToObject<object>()) : new Dictionary<string, object>(); }
            set { AttributeTokens = value.ToDictionary(x => x.Key, x => x.Value == null ? null : JToken.FromObject(x.Value)); }
        }

        [JsonExtensionData]
        public Dictionary<string, JToken> AttributeTokens { get; set; }

        [JsonIgnore]
        public IEnumerable<AttributeValue> AttributeValues
        {
            get { return Attributes.Select(x => new AttributeValue { Name = x.Key, Value = x.Value }); }
            set { Attributes = value.ToDictionary(x => x.Name, x => x.Value); }
        }

        public override string ToString()
        {
            return FullName + " (" + Id + ")";
        }
    }
}

我的问题是在我的视图上面的每个下面... @ Html.EditorFor(x.User.Username)有一个重载,typeof(string).FullName。 @ Html.EditorFor(x.User.Username,typeof(string).FullName,new {placeholder =“blah”})

基本上更改了我的编辑器的名称,因此每个客户端@ Html.ValidationMessageFor(x.User.Username)代码都不会激活。

此外,如果我从@ Html.EditorFor实例中删除typeof(string).FullName,我的客户端验证将开始工作,但是在保存时,它会将空值传递给相关的控制器,因此具有所有空白信息的用户得到了。

  1. 为什么以前的开发人员使用过这种typeof(string).FullName的东西,究竟是什么呢?
  2. 如何摆脱这种类型(字符串).FullName并且它适用于我的模型(即,在提交给控制器时不发送空值。)以便客户端验证有效?
  3. 我可以使用typeof(字符串).FullName来进行客户端验证吗?
  4. 非常感谢您的帮助!!

    Solution Explorer Solution Explorer Screenclip @ 42shadow42 Views/Shared/EditorTemplates

    UPDATE - UsersController.cs

    [Route("person/add"), HttpPost]
    public new async Task<ActionResult> Add(string email,  string username, string firstName, string lastName, string snippet, string bio, bool isAmbassador = false, bool isTeam = false, Gender gender = Gender.None, string location = null, DateTime? birthdate = null, 
        string twitterHandle = null, string facebookPageId = null, string wikipediaUrl = null, bool marketingEmails = false, string[] roles = null)
    

1 个答案:

答案 0 :(得分:0)

  1. typeof(string).FullName指示MVC使用名为System.String.cshtml的编辑器模板

  2. 可能见下文。

  3. 是的,请参阅下文,具体取决于2,这可能会或可能不会修复您的模型装订。

  4. 3

    的解决方案

    尝试将此用于您的System.String.cshtml,如果我更正,它应该呈现相同的html样式和格式,内置支持您正在使用的验证属性。

    <div class="row">
        @Html.LabelFor(model => model , new { @class = "col-xs-2" })
        @Html.TextBoxFor(model => model , new { @class = "col-xs-10" })
    </div>
    

    解决方案#1 for 2

    如果此时没有建模绑定,您可能需要更改主视图的一部分:

    替换:

            <div>
                @Html.EditorFor(x => x.User.Username, typeof(string).FullName, new { @class = "form-control" })
            </div>
            <div class="row">
                @Html.ValidationMessageFor(x => x.User.Username, "", new { @class = "text-danger" })
            </div>
    

    使用

                <div>
                    @Html.EditorFor(x => x.User.Username, typeof(string).FullName, "Username", new { @class = "form-control" })
                </div>
                <div class="row">
                    @Html.ValidationMessageFor(x => x.User.Username, "", new { @class = "text-danger" })
                </div>
    
    <2>解决方案#2 for 2

    或者,您可以只更新控制器操作方法签名以使用参数名称&#34; User&#34;。像这样:

    public ActionResult Edit(User User){
    }