selestian
selestian

Reputation: 1

MVC Render data issue

I've created a simple mvc webage with textarea. I submit data to server and then I need to refresh view. But textarea always contains browser data, but my model has changed.

Debug shows me:

Html.TextArea("EmailBody", Model != null ? Model.EmailBody : "Message") 
{<textarea cols="20" id="EmailBody" name="EmailBody" rows="2"> Message</textarea>}  System.Web.Mvc.MvcHtmlString {System.Web.Mvc.{Dynamic}.DynamicMvcHtmlString}

But at the same time

Model != null ? Model.EmailBody : "Message" "123"   string

i.e. rendering on page differs from real data (real data is 123, but I get old data typed in textarea). Please, advice.

Problem resolved with

<textarea id="EmailBody" name="EmailBody"><%= Model.EmailBody %></textarea>

Thanks a lot.

Upvotes: 0

Views: 129

Answers (1)

Jason Evans
Jason Evans

Reputation: 29186

I would use

@Html.TextAreaFor(model => model.EmailBody, .....

and in my controller:

public ActionResult Index()
{
  var viewModel = new MyViewModel();

  viewmodel.EmailBody = "Default";

  return this.View(viewModel);
}

[HttpPost]
public ActionResult Index(MyViewModel inputViewModel)
{
  string body = inputViewModel.EmailBody // Whatever....
}

The key point is don't bother passing a NULL viewmodel to your view, give it some default data to work with. That way, you can use the HTML helpers like TextBoxFor() or TextAreaFor() to render for you.

Upvotes: 2

Related Questions