简体   繁体   English

修剪我的asp.net mvc中的字符串的最佳方法

[英]Best way to trim the strings inside my asp.net mvc

I have a string field name consoleServerPort, and I want to trim all the white spaces inside it before saving it. 我有一个字符串字段名称consoleServerPort,我想在保存之前修剪其中的所有空格。 I use to do so inside my controller class, as follow:- 我在我的控制器类中使用,如下所示: -

public ActionResult Edit(FirewallJoin fj, FormCollection formValues)
        {
fj.ConsoleServerPort = !String.IsNullOrEmpty(fj.ConsoleServerPort) ? fj. ConsoleServerPort.Trim() : "";

But I have to repeat this step on every action method. 但我必须在每个行动方法上重复这一步骤。 So I found another way of doing so once at the model level inside an Ivalidatable method as follow:- 所以我在Ivalidatable方法中的模型级别找到了另一种方法,如下所示: -

public partial class TMSFirewall : IValidatableObject
    {
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if(!String.IsNullOrEmpty(ConsoleServerPort)){
                ConsoleServerPort = ConsoleServerPort.Trim();
            }

So is my second approach sound valid? 那么我的第二种方法听起来有效吗? or it is better to use the first approach ? 或者最好使用第一种方法? Thanks 谢谢

Edit I am using entity Framework and i did the following i tried the following inside my model class i added the following :- 编辑我正在使用实体框架,我做了以下我在我的模型类中尝试了以下内容我添加了以下内容: -

[MetadataType(typeof(TMSSwitchPort_Validation))]
    [Bind(Include = "PortNumber,SwitchID,TechnologyID")]
    public partial class TMSSwitchPort //: IValidatableObject
    {

    }

then inside the MetadataType class i added the following :- 然后在MetadataType类中添加了以下内容: -

public class TMSSwitchPort_Validation
    {
        private string consoleServerPort;

        [Required]
        [StringLength(10)]
        [Display(Name="Port Number1111")]
        public String PortNumber
        {
            get { return this.consoleServerPort; }
            set { this.consoleServerPort = value.Trim(); }
        }


    }

but the ConsoleServerPort will not be trimmed? 但ConsoleServerPort不会被修剪? can you advice what might be the problem ? 你能建议可能出现什么问题吗?

Thanks 谢谢

Couldn't you do it on the property setter? 你不能在物业设定者那里做吗?

public class FirewallJoin
{
     private string _consoleServerPort;
     public string ConsoleServerPort
     {
         get
         {
               return _consoleServerPort;
         }
         set
         {
             _consoleServerPort = value.Trim();
         }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM