【问题标题】:How to pass text value to action parameter?如何将文本值传递给动作参数?
【发布时间】:2019-05-29 05:09:43
【问题描述】:

我需要将输入值传递给控制器​​中的操作方法

我有文本和按钮,所以我需要单击按钮并将输入的值传递给参数,然后重新回到相同的视图,但处于发布状态

我尝试了很多东西,但没有用

我尝试创建帖子表单,按钮类型是提交但不起作用

这是我的视图代码

<form method="post">
    <input  type="text" id="Comments" , name="ID" value="" />
    <button type="submit">Go</button>

</form>

这是我的控制器代码

 public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }

【问题讨论】:

    标签: asp.net-mvc model-view-controller


    【解决方案1】:

    在您的视图模型中使用@Html.BeginForm 重定向到控制器中的操作方法。

    可见

    @using (Html.BeginForm("youractionname", "yourcontrollername",FormMethod.Post, new { @class = "form-horizontal"}))
    {
    <input type="text" id="Comments" name="ID" />
        <button type="submit">Go</button>
    }
    

    在控制器中

    public ActionResult Index()
            {
                Entities db = new Entities();
                var Query = from acc in db.tbl_Accounts
                            select acc ;
    
                var accList= Query.ToList<tbl_Accounts>();
                return View(accList);
    
            }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;
    
            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);
    
        }
    

    您在操作方法中采用了整数数据类型,以便在文本框中输入数字值

    注意:请在视图模型中验证您的操作和控制器名称

    【讨论】:

      【解决方案2】:

      您的代码中有一些拼写错误,如果您按以下方式更正它,它将按预期工作:

      <form method="post">
          <input type="text" id="Comments" name="ID" />
          <button type="submit">Go</button>
      </form>
      

      所以现在只检查参数值,如果有的话:

      [HttpPost]
      public ActionResult Index(int ID)
      {//Put a breakpoint here and check if ID has value
      
         return View();
      }
      

      如果该值存在,则假设它是可以的。

      这是我已经测试过这个答案的screenshot

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 1970-01-01
        • 1970-01-01
        • 2012-01-31
        • 1970-01-01
        相关资源
        最近更新 更多