Richard Aguirre Richard Aguirre - 3 months ago 7
ASP.NET (C#) Question

I don't get back the changes of my model in my View Mvc

I am starting in asp.net Mvc and making test, i am doing a simple chat using PubNub api and i want finish it using only razor code only and one page only. Let see what i have:

Model Chat.cs:

namespace SimpleChat.Models
{
public class Chat
{

public string NuevoMensaje { get; set; }
public string TextArea { get; set; }
}
}


View:

@model SimpleChat.Models.Chat

@using (Html.BeginForm("Index","Chat",FormMethod.Post))
{
@Html.LabelFor(model => model.NuevoMensaje, "Nuevo Mensaje")
@Html.TextBoxFor(model => model.NuevoMensaje) <input type="submit" class="btn-default" value="Enviar" />
@Html.TextAreaFor(model => model.TextArea)


}


Controller:

static string variante = "";
public ActionResult Index()
{
pubnub.Subscribe<string>("Chat", subCallback, connecCallBack, errorCallback);
//Chat nuevochat = new Chat();
return View();
}


[HttpPost]
public ActionResult Index(Chat chat)
{
pubnub.Publish<string>("Chat", chat.NuevoMensaje, userCallback, puberror);
chat.NuevoMensaje = "";
chat.TextArea =variante;
return View("Index",chat);
}
private void subCallback(string obj)
{
string[] retorno = obj.Split(',','"');
variante += "Richard dice:" + retorno[0] + "\n";
}


When i press submint don't get the new data, why?

Answer

If you want to render the updated value of TextArea property of your view model, You should clear the model state dictionary.

Model state dictionary has the initial values of your form inputs. So when razor (re)render the same view, It gives priority to the content in model state dictionary than the view model object you passed to the view.

You can use the ModelState.Clear() method to clear the model state dictionary values before returning to the view.

chat.TextArea = variante; 
ModelState.Clear();
return View("Index",chat);

Assuming your variante variable has the updated text.