Note that there are some explanatory texts on larger screens.

plurals
  1. POhtml.TextArea() value after PostBack
    text
    copied!<p>I'm new to MVC and I'm using Razor. I have a form where the user can edit text fields then click save. Here's my form</p> <pre><code>@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "form" })) { ... @Html.TextArea("Description", Model.Description, 5, 50, null) ... } </code></pre> <p>After I tested this and verified it was working, I added some server side checking. For the description field, I checked that it wasn't blank. If it wasn't then display an error message. Here's my code for this</p> <pre><code>[HttpPost] public ActionResult EditContract(Contract contract) { if (contract.Description == null) { contract.Description = string.Empty; } contract.Description = contract.Description.Trim(); if (contract.Description == string.Empty) { ViewBag.Message = "Description can't be blank"; contract.LoadContract(contract.ContractId); return View(contract); } ... } </code></pre> <p>This actually all worked as I wanted. However, I was surprised that it did. My code loaded the record from the database and passed it to the view as the model. How did the view know not to set the value of the textbox to the value from the model and leave it as what the user last entered?</p> <p><strong>EDIT</strong></p> <p>I created a simple project to test this out thinking something in my project could be effecting how this is working. This simple project is an empty MVC 4 project using razor. I then added the following code.</p> <p>MyModel.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication6.Models { public class MyModel { public string Name { get; set; } } } </code></pre> <p>HomeController.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication6.Models; namespace MvcApplication6.Controllers { public class HomeController : Controller { public ActionResult Index() { var myModel = new MyModel(); return View(myModel); } [HttpPost] public ActionResult Index(MyModel model) { model.Name = "something"; return View(model); } } } </code></pre> <p>Index.cshtml</p> <pre><code>@model MvcApplication6.Models.MyModel @using (Html.BeginForm()) { @Html.TextBoxFor(model =&gt; model.Name) &lt;br /&gt; &lt;input type="submit" value="submit" /&gt; } </code></pre> <p>I would like it to show 'something' in the textbox after the user clicks submit but it doesn't. It has whatever the user has previously entered. What do I need to do to get it to show 'something'?</p> <p>Thanks,</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload