簡體   English   中英

從表單提交中刪除空格

[英]Removing Whitespace from Form Submission

當用戶填寫我的表單來創建一個新的Person時,我希望在名稱之前或之后沒有空格( String類型)。

Good :“John Doe”

Bad :“John Doe”或“John Doe”

看看這篇SO 帖子 ,似乎我想使用自定義的ModelBinder。 但是,由於我可能錯誤地理解了帖子,因此替換我的DefaultModelBinder將意味着不允許所有字符串具有前導或尾隨空格。

我怎樣才能確保只有Name的由這個自定義ModelBinder的影響?

您可以將此行為直接寫入視圖模型(如果您使用的是視圖模型):

private string name;

public string Name
{
    get { return this.name; }

    set { this.name = value.Trim(); }
}

然后Name將在您的控制器操作方法中預先修剪。

您可以使用修剪功能。 來自MSDN,

Trim方法從當前字符串中刪除所有前導和尾隨空格字符。

您可以在房產中提到名稱,例如:

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }

然后,您可以在上面提到的帖子中使用以下修改后的代碼作為Custom Model粘合劑解決方案:

public class TrimModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        if (propertyDescriptor.Name.ToUpper().Contains("NAME")
             && (propertyDescriptor.PropertyType == typeof(string)))
        {
            var stringValue = (string) value;
            if (!string.IsNullOrEmpty(stringValue))
                stringValue = stringValue.Trim();

            value = stringValue;
        }

        base.SetProperty(controllerContext, bindingContext,
                         propertyDescriptor, value);
    }
}

這樣,在其中命名並且是字符串類型的任何名稱屬性都將在此處修剪空白區域。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM