2016-01-29 233 views
4

我有3个文本框,第一个是数量,第二个是价格,第三个是总价格。如何在Asp.net MVC中将两个文本框的值相乘

<div class="form-group"> 
      @Html.LabelFor(model => model.quantity, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.quantity, new { htmlAttributes = new { @class = "form-control", @type = "number" } }) 
       @Html.ValidationMessageFor(model => model.quantity, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.price, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.price, new { htmlAttributes = new { @class = "form-control", @type = "number" } }) 
       @Html.ValidationMessageFor(model => model.price, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.totalprice, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
        @Html.EditorFor(model => model.totalprice, new { htmlAttributes = new { @class = "form-control", @type = "number" } }) 
        @Html.ValidationMessageFor(model => model.totalprice, "", new { @class = "text-danger" })    
      </div> 

这里是控制器:

 [HttpPost] 
     public ActionResult Add(Model model) 
     { 
      obj.Quantity = model.quantity; 
      obj.Price = model.price; 
      obj.TotalPrice = model.totalprice 

      db.Details.Add(obj); 
      db.SaveChanges(); 
      return RedirectToAction(""); 
     } 

现在我想乘第一和第二文本框的值,并将其在第三文本框。例如,如果用户在第1个文本框中输入5,在第2个文本框中输入100,则它会在第3个文本框中自动显示500,如果用户更改第1个或第2个文本框的值,则第3个文本框的值也会相应更改。 谢谢。

+1

将文本从前两个框转换为整数,然后将两个文本相乘,将该结果转换为字符串并将其放置在第三个文本框中。 –

+0

谢谢,但我怎样才能得到前两个文本框的值? 我们没有选项可以通过MVC中的textbox.Text获取值,还有其他解决方案吗? – diamond421

+0

看一看[BeginForm(https://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(V = vs.118)的.aspx)来发表您的模型到控制器。 – GuyVdN

回答

4

你可以听在JavaScript中keyup事件的文本框,读出的值,做乘法,并将所得值设置为第三文本框。

假设您的页面中包含jQuery库。

$(function(){ 

    $("#quantity,#price").keyup(function(e){ 

    var q=$("#quantity").val(); 
    var p=$("#price").val(); 
    var result=""; 

    if(q!=="" && p!=="" && $.isNumeric(q) && $.isNumeric(p)) 
    { 
     result = parseFloat(q)*parseFloat(p); 
    } 
    $("#totalPrice").val(result); 

    }); 

}); 

Here是一个正在运行的jsbin示例。

0

您可以使用此:

[HttpPost] 
    public ActionResult Add(Model model) 
    { 
     obj.Quantity = model.quantity; 
     obj.Price = model.price; 
     obj.TotalPrice = model.totalprice 

     model.totalprice = model.quanity * model.price 
     db.Details.Add(obj); 
     db.SaveChanges(); 
     return RedirectToAction(""); 
    } 

希望它能帮助。我在我的应用程序中使用它,它做对了。

相关问题