【问题标题】:Passing html textbox value as a parameter to controllers method in asp.net MVC将html文本框值作为参数传递给asp.net MVC中的控制器方法
【发布时间】:2013-12-18 15:53:28
【问题描述】:

我想将Html.Textbox 值从锚标记传递给控制器​​,以便我可以搜索传递给控制器​​的值。请告诉我如何才能做到这一点。

<a  href="@Url.Action("Index", "Home", new {  })">@p</a>

public ActionResult Index(string String)
        {


        }

@Html.TextBox("String")

【问题讨论】:

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


    【解决方案1】:

    使用 jquery

    @Html.TextBox("String", null, new { @class="txtString" })
    <a  href="@Url.Action("Index", "Home", new {  })" class="linkAction">@p</a>
    

    然后在你的脚本中

    $('.txtString').on('blur', function(){
        $('.linkAction').attr('src', '@Url.Action("Index", "Home", new { text = "----" })'.replace("----", $('.txtString').val()));
    });
    

    【讨论】:

    • 它在文本框中显示 { class= txtString }。有没有语法错误。
    • 抱歉将类放入对象值而不是 html 值。为对象值添加了一个空值,因此它现在应该正确呈现
    【解决方案2】:

    您不必使用 jQuery。如果你正在做一个HttpPost,你只需要文本框的“名称”。

    在您的页面上:

    @using (Html.BeginForm("Index", FormMethod.Post)) {
        @Html.TextBox(string.Empty, new { name = "textbox" })
    
        <input type="submit">Submit</input>
    }
    

    然后在你的控制器中:

    [HttpPost]
    public ActionResult Index(string textbox) {
        // The name of the string parameter must match the name given to the TextBox element on the page.
    }
    

    【讨论】:

    • 我可以在传递页码时借助锚标签传递名称吗:@p
    • 为此,您必须使用 jQuery 和 Matt Bodily 的答案。使用这样的表单实际上是一种更可接受的做事方式,因为您希望从服务器上的客户端检索动态信息。这完全取决于您如何使用它,以及您要遵循哪种约定。
    • string.empty 应该是 string.Empty 大写:E
    【解决方案3】:
    @using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new {@id = "my-form"}))
    {
        @Html.TextBox("String")
    }
    
    <a href="javascript:document.getElementById('my-form').submit();>@p</a>
    

    您可以使用FormMethod.PostFormMethod.Get。后者会将 ?String= 附加到 url。

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多