0

I'm trying to set the sum of two Textboxes to another Textbox using ASP.NET MVC, I know this looks easy but I'm not familiarized with MVC. I just have done this just by using a @ViewBag.mensaje. This is my code:

Model:

public class suma
{
    public int n1 { get; set; }
    public int n2 { get; set; }
    public int total { get; set; }
}

Controller:

  // GET: suma

  public ActionResult Index()
  { 
      return View();
  }

  [HttpPost]
  public ActionResult Index(Models.suma model) 
  {
        int x = model.n1;
        int y = model.n2;
        int total = model.total;
        total = x + y;
        ViewBag.mensaje = (total).ToString();
        return View();
  }

View:

@model bonito2.Models.suma

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@using (Html.BeginForm("Index", "suma", FormMethod.Post))
{

    @Html.TextBoxFor(model => model.n1)<br />
    @Html.TextBoxFor(model => model.n2)<br />
   <input type="submit" value="Submit" /> <br />

    @ViewBag.mensaje
}

My code works OK but I'm trying this to work or set the value on a Textbox not in a @ViewBag.mensaje. Thanks.

1
  • For example add Total property to your model, and on get method write return n1 + n2 (or calculate inside ActionMethod). Commented Mar 6, 2019 at 8:04

2 Answers 2

2

You can simply do as follows:

public class suma
{
    public int n1 { get; set; }
    public int n2 { get; set; }
    public int total => n1 + n2;
}

Then in the html:

@Html.TextBoxFor(model => model.total)
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this but It didn't work, @Html.TextBoxFor(model => model.total) created a new textbox but sum didnt work. It just appear to be blank after clicking button. What am I missing?
0

js code

 $(document).ready(function() {
        //this calculates values automatically 
        sum();
        $("#n1, #n2").on("keydown keyup", function() {
            sum();
        });
    });
function sum() {
            var num1 = document.getElementById('n1').value;
            var num2 = document.getElementById('n2').value;
            var result = parseInt(num1) + parseInt(num2);
            if (!isNaN(result)) {
                document.getElementById('total').value = result;
            }
        }

and add this to html

<input type="text" name="total" id="total" readonly />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.