Search code examples
asp.netasp.net-mvcasp.net-mvc-4razor-2

Addition of two numbers in MVC


I am trying to add two numbers in MVC.

My requirement is "I have 2 text boxes in View from which I have to retrieve data to controller"

View :

@using (Html.BeginForm("Addition", "Addition", FormMethod.Post))
{
    <input id="Text1" type="text" [email protected] name="firstNum" />
    <input id="Text2" type="text" [email protected] name="secondNum" />
    <input id="Text3" type="text" [email protected] />

    <input type="submit" value="Submit" />
}

Controller Name : Addition Action Name: Addition

[HttpPost]
        public ActionResult Addition(FormCollection fc)
        {
            string[] keyss = fc.AllKeys;
            ViewBag.a = fc.Keys[0];
            ViewBag.b = fc.Keys[1];
            ViewBag.total = ViewBag.a + ViewBag.b;
            return View();
        }

Now, from this form collection I want to retrieve values of textboxes.

Thanks.


Solution

  • One of the powers of MVC is the model binder - which you are completely ignoring here. Create a view model to match the expected content of your view

    public class AdditionViewModel
    {
        public int A { get; set; }
        public int B { get; set; }
        public int Result { get; set; }
    }
    

    Use this as the expected parameter in your action

    [HttpPost]
    public ActionResult Addition(AdditionViewModel model)
    {
        model.Result = model.A + model.B;
        return View(model);
    }
    

    Then finally in your view

    @model AdditionViewModel
    
    @using (Html.BeginForm("Addition", "Addition", FormMethod.Post))
    {
        @Html.EditorFor(x => x.A)
        @Html.EditorFor(x => x.B)
        @Html.DisplayFor(x => x.Result)
    
        <input type="submit" value="Submit" />
    }