简体   繁体   中英

ASP.NET MVC 5 Trim string on postback?

During a postback (lets assume validation errors) my text input fields do not display trimmed values even though I specify them to be so in my model (see simple model below). The values are indeed trimmed under my controller, debug.writeline() shows them so, but that isn't being reflected in the view.

How do I get that trimming to reflect in my view (within an Input Field) after a postback?

Simple model:

private string _name;

public string Name {
    get { return this._name; }
    set { this._name = (value == null) ? "" : value.Trim(); }
}

Simple controller:

public ActionResult Index() {
    return View();
}

[HttpPost]
public ActionResult Index([Bind(Include="Name,City,State")] Model model) {

    Debug.WriteLine("Name: " + model.Name);  // trimmed!

    return View(model);
}

Simple view:

@using(Html.BeginForm()) {
    @Html.EditorFor(m => m.Name);   // not trimmed!
    @Html.ValidationMessageFor(m => m.Name);
}

UPDATE: In my Simple Controller, the HttpPost method, I'm passing my model to the view "return View(model)". In my view I can reference that object simply by doing "Model.Name" or "@Model.Name" and when I do so, I see that it is trimmed. The problem however still remains because I do not understand how to reference the passed in object (model) under @Html.LabelFor, @Html.EditorFor helpers? I did try using @Html.Label and @Html.Editor in some creative ways, but that didn't work either. If I understand the helper objects, then @Html.EditorFor(m => m.Name) is actually not referencing the passed in object (model) but instead creating a new reference to it.

Under View:

@{
    Layout = null;

    if (Model != null) {
        Debug.WriteLine("From View: _" + Model.Name + "_");  // trimmed !
    }
}

Posted the same question on ASP.NET and received a response from @ignatandrei (marked as answer). In short, the problem has to do with how the @Html.Helpers process incoming data. @ignatandrei explains:

"The data comes to MVC from POST --> GET --> MODEL (in this order), for your problem, [use] ModelState.Remove("Name") [in the Controller]."

http://forums.asp.net/p/2002010/5754373.aspx?ASP.NET+MVC+5+Trim+string+on+postback+

Doing further research I found the following article which nicely explains ModelState (amongst others), Html.Helpers and Views (and their relationships).

http://www.gxclarke.org/2010/05/consumption-of-data-in-mvc2-views.html?m=1

UPDATE: Here's an article that explains the problem (and possible solutions) perfectly: http://weblog.west-wind.com/posts/2012/Apr/20/AS.NET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes

Try this:

private string _name;

public string Name {
get { return ((this._name != "" && this._name != null ) ? this._name.Trim():this._name); }
set { this._name = (value == null) ? "" : value.Trim(); }
}

In Order to apply Trim on every string model property in asp.net mvc than follow this link:

http://puredo.netcoder.blogspot.in/2011/12/automatically-trim-html-controls-in.html

OR

ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?

If you don't want to mess around with the model state (see https://stackoverflow.com/a/25282083/2279059 ) or rely on implementation details of .NET/Razor (which is perfectly fine in this case), you can also solve this by creating separate properties.

For example, you can have a FormName property, which is the value entered into the form and a Name property, which is the trimmed/validated property, which is set whenever FormName is set, and which you use for rendering the view as well as application logic.

Try this on view, replace modelfield with your model field name in asp-for="ModelField" and @Model.modelfield.trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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