【问题标题】:Asp.net MVC Get Textbox Value In ViewAsp.net MVC 在视图中获取文本框值
【发布时间】:2023-03-21 16:37:02
【问题描述】:

所以我有一个输入框

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

我如何获取它的价值?

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

谢谢。

【问题讨论】:

  • 由于quantity的值可以在客户端更改,您需要使用javascript构建查询字符串(@Html.ActionLink在发送到客户端之前在服务器上解析)
  • 我如何将查询字符串传递给 Html.ActionLink? mvc 新手。
  • 你不会因为@Html.ActionLink是在服务器上生成的。这就是为什么您需要使用 javascript/jquery 生成 href 属性并使用 window.location.href = "..."; 如果您需要示例,请告诉我

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以像这样将值发送到控制器的操作:

    控制器动作:

    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&quantity=1”

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-03
        • 2011-03-03
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多