Cristina
Cristina

Reputation: 69

Update a field in view based on the model in ASP.NET MVC

I need to do a calculator in ASP.NET MVC. For the beginning I want to receive the value from the input field in controller and prefix it with the string "123". At the end I will process the expresion received and return the result.

I have the following model:

namespace CalculatorCloud.Models {
    public class Calculator
    {
        public string nr { get; set; }
    } }

In the view I am using the model:

@model CalculatorCloud.Models.Calculator

@{
    ViewBag.Title = "Calculator";
}

@using (Html.BeginForm("Index", "Home"))
{
<div>
    <div class="header">
        @Html.TextBoxFor(m => m.nr, new { @id = "nr"})
        <input type="button" id="C" name="C" value="C" />
        <input type="button" id="back" name="back" value="<-" />
[...]

    <div class="sum">
        <input type="submit" value="=" />
    </div>
</div>
}

The controller is like this:

namespace CalculatorCloud.Controllers
{
    public class HomeController : Controller
    {
        Calculator model = new Calculator();

        public ActionResult Index(string nr)
        {
            model.nr = "123" + nr;
            return View(model);
        }

    }
}

I have the following problem: when pressing on submit button I am expecting to be displayed on the textbox the value from that was previously in the textbox, prefixed with the string "123". But now it is kept the value from the textbox without the string "123".

Can someone help me with this? Thank you! :)

Upvotes: 1

Views: 1593

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

If you want to modify the value of a model property in a postback action you will need to remove it from the ModelState:

public ActionResult Index(string nr)
{
    ModelState.Remove("nr");
    model.nr = "123" + nr;
    return View(model);
}

The reason for this is that Html helpers such as TextBoxFor will first look at the value present in the ModelState and then in your view model property when rendering the value. This is by design.

Upvotes: 2

Related Questions