2014-10-10 62 views
-1

所以我有一个输入框Asp.net MVC获取文本框的值在View

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

如何访问它的价值呢?

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

谢谢。

+1

由于quantity'的'值可以在客户端上进行更改,则需要使用JavaScript来构建查询字符串('@ Html.ActionLink'被解析的服务器发送到客户端之前) – 2014-10-10 00:50:20

+0

如何将查询字符串传递给Html.ActionLink?新的mvc。 – Teddy 2014-10-10 00:52:44

+0

你不会因为在服务器上生成了@ Html.ActionLink。那为什么你需要使用javascript/jquery生成'href'属性并使用'window.location.href =“...”;'如果你需要一个例子让我知道 – 2014-10-10 00:57:23

回答

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 
}) 
0

你可以得到发送到控制器的动作像THI值:

控制器操作:

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提交的数据为 “/车/ addToCart” 您的浏览器将链接到类似:“HTTP:1234/?/车/ addToCart /条=苹果&量= 1"

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