2016-01-29 232 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(""); 
    } 

希望它能幫助。我在我的應用程序中使用它,它做對了。

相關問題