2

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 !
    }
}
  • You should probably make `Trim()` in a getter? – Artyom Neustroev Aug 12 '14 at 09:22
  • Can you show the `Get` & `Post` controller methods? – Kaf Aug 12 '14 at 09:23
  • Edited, added Simple Controller. –  Aug 12 '14 at 09:26
  • just try below answer – Kartikeya Khosla Aug 12 '14 at 09:27
  • Try this line `Debug.WriteLine("Name:_" + model.Name + "_");` to make sure no spaces. – Kaf Aug 12 '14 at 09:28
  • Kaf, yes -- I was able to confirm the value is trimmed in the debug output. –  Aug 12 '14 at 09:30
  • After posting back, your view shows `ModelState` values not `Model` values. I think it could be the reason you having a different value in view compared to the controller. You need to change the `Name` value in the `ModelState` within the controller. [This post might help](http://stackoverflow.com/questions/19982876/dropdownlistfor-not-always-showing-selected-value/19983428#19983428). In addition, trim the values in getter as well. – Kaf Aug 12 '14 at 10:45
  • http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo – Korayem Jul 27 '16 at 06:57

4 Answers4

1

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/ASPNET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes

0

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://puredotnetcoder.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?

Community
  • 1
  • 1
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • I'll give that a shot, but on post isn't the value SET then? After which a GET should return the trimmed value? –  Aug 12 '14 at 09:28
  • yes...but i think above answer will solve problem just give it a try..@JasonCaldwell.... – Kartikeya Khosla Aug 12 '14 at 09:29
  • @JasonCaldwell...read this...http://puredotnetcoder.blogspot.in/2011/12/automatically-trim-html-controls-in.html – Kartikeya Khosla Aug 12 '14 at 09:46
  • that looks promising. –  Aug 12 '14 at 09:57
  • @JasonCaldwell...it is working i have used it..just check there must be problem somewhere else..or visit this http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo – Kartikeya Khosla Aug 13 '14 at 06:52
  • Exception, thanks. It didn't work for me, plus its really not the right solution for me had it worked. I received a correct answer from someone at ASP.NET today, see below. Appreciate your help. –  Aug 13 '14 at 09:01
0

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.

Florian Winter
  • 4,750
  • 1
  • 44
  • 69
0

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