Asp.net MVC在视图中获取文本框值

时间:2014-10-10 00:46:53

标签: c# asp.net asp.net-mvc

所以我有一个输入框

<input type='text' name='quantity' value='1'/>

如何访问它的值?

@Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", new { id = Model.ProductID, quantity = IWANTTHEVALUEHERE } "")

感谢。

3 个答案:

答案 0 :(得分:0)

@Html.ActionLink在将服务器发送到浏览器之前为其生成链接的html。由于可以在浏览器中更改quantity的值,因此您需要使用javascript / jquery更新链接href属性。

查看

<input type='text' id="quantity" name='quantity'> // give it an id
// no point adding route parameters yet since they will be changed on the client
@Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", null, new { id = "myLink" })

脚本(让你包含jquery.js文件)

$('#myLink').click(function (e) {
  e.peventDefault(); // stop default redirect
  var id = '@Model.ProductID';
  var quantity = $('#quantity').val(); // get the quantity from the textbox
  var href = $(this).attr('href'); //  get current href value
  href = href + '?id=' + id + '&quantity=' + quantity; // update with parameters
  window.location.href = href; // redirect
})

答案 1 :(得分:0)

您可以获取发送到控制器操作的值,如thi:

Controller Action:

public class CartController {

   // controller action
   [HttpGet]
   public void addToCart(string item, int quantity)
   {
      return "Your cart now contains: " + quantity + " " + itemName;
      // You may do something else
   }
}

观点:

<form method="GET" action="/Cart/addToCart">
   <input type='text' name="item" value='apple'>
   <input type='text' name="quantity" value="1">
   <input type="submit" value="Add to Cart">
</form>

输出:

"Your cart now contains 1 apple."

表单将通过GET将数据提交到“/ Cart / addToCart” 您的浏览器将链接到以下内容:“http:1234 // Cart / addToCart /?item = apple&amp; quantity = 1”

答案 2 :(得分:0)

试试这个:

<input type='text' id='qty' name='quantity' value='1'/>

@Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", new { id = "link" })

并在您的javascript中添加此内容:

$('#link').click(function () {
  var id = '@Model.ProductID';
  var quantity = $('#qty').val(); 
  window.location = '@Url.Action("Action", "Controller")?id=' + id + '&quantity=' + quantity;
})