Domanda

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" value=@ViewBag.a name="firstNum" />
    <input id="Text2" type="text" value=@ViewBag.b name="secondNum" />
    <input id="Text3" type="text" value=@ViewBag.result />

    <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.

È stato utile?

Soluzione

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" />
}

Altri suggerimenti

Assuming you get the data in to ur controller , afterwards you just add Addition view and use @ViewBag.total simple or you also can use viewdata or tempdata in case if u required .

The better way is

  [HttpPost]
  public ActionResult Addition(int firstNum, int secondNum )
  {
   ViewBag.Result=firstNum+secondNum;
   return View();

  }

Make sure you are doing a Numeric validation at client side

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top