【问题标题】:How to set the sum value on another Textbox using ASP MVC如何使用 ASP MVC 在另一个文本框上设置总和值
【发布时间】:2019-03-06 08:02:37
【问题描述】:

我正在尝试使用 ASP.NET MVC 将两个文本框的总和设置到另一个文本框,我知道这看起来很容易,但我不熟悉 MVC。我只是通过使用@ViewBag.mensaje 来完成此操作。这是我的代码:

模型

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

控制器:

  // 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();
  }

查看:

@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
}

我的代码工作OK,但我正在尝试这个工作或在文本框上设置值而不是@ViewBag.mensaje。谢谢。

【问题讨论】:

  • 例如将Total 属性添加到您的模型中,并在get 方法上写入return n1 + n2(或在ActionMethod 中计算)。

标签: c# asp.net asp.net-mvc model-view-controller


【解决方案1】:

您可以简单地执行以下操作:

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

然后在html中:

@Html.TextBoxFor(model => model.total)

【讨论】:

  • 我试过了,但没用,@Html.TextBoxFor(model =&gt; model.total) 创建了一个新的文本框,但总和没有用。单击按钮后它似乎是空白的。我错过了什么?
【解决方案2】:

js代码

 $(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;
            }
        }

并将其添加到 html

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多