Pregunta


I have some strange errors in displaying model. I am creating something like chat. Users sending messages between yourself. When user selected one message in his inbox, and has clicked on the button "Answer", for example, form send submit(). Then information about selected message is displaying.

And in this moment I have a problem. If fields, that's displaying message properties are @Html.DisplayFor(), all works fine. Info of the message refreshed with change of selected message. But if properties displaying with @Html.TextAreaFor or Html.TextBoxFor it didn't happend with changing selected message.

And, if user clicked on "view" button, which display model in @Html.DisplayFor() model displaying refresh, and refresh in @Html.DisplayFor() many many times. And as soon as click on "Answer" button, ie dipaly model in @Html.TextBoxFor(), model stopped to refresh display on changing selected message.

I drawed an image, for easier understanding. :) enter image description here

Many Many Thanks!

¿Fue útil?

Solución

I guess you are modifying the value you have bound the TextBoxFor on the HttpPost action:

[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
    model.SomeProperty = "some new value";
    return View(model);
}

and in the view you have:

@Html.TextBoxFor(x => x.SomeProperty)

If so, then this is by design. The HTML input helpers (such as TextBoxFor, TextAreaFor, CheckBoxFor, ...) are first looking in the ModelState when rendering their values and only after that in the model itself. So if you intend to modify some of the model properties in your POST action make sure that you remove it from the ModelState:

[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
    ModelState.Remove("SomeProperty");
    model.SomeProperty = "some new value";
    return View(model);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top