【问题标题】:Passing input value to action (ASP.Net MVC 3)将输入值传递给操作(ASP.Net MVC 3)
【发布时间】:2016-03-21 18:29:48
【问题描述】:

我在视图中有代码:

@using (Html.BeginForm("MyAction", "MyController")
{
    <input type="text" id="txt" />          
    <input type="image" src="/button_save.gif" alt="" />
}

如何将 txt 的值传递给我的控制器:

[HttpPost]
public ActionResult MyAction(string text)
{
 //TODO something with text and return value...
}

【问题讨论】:

  • 我相信,如果你想让自动绑定工作,你的控制器参数的名称必须与你的输入框的 id 匹配,即string txt
  • 无论如何,让控件绑定到您可以使用的某个对象的最佳方法是从ViewData 对象继承页面,并将ViewData 对象指定为您的参数控制器方法。有关详细信息,请参阅 NerdDinner 教程。 nerddinnerbook.s3.amazonaws.com/Part6.htm
  • 非常感谢!我也试试。

标签: asp.net-mvc-3 razor


【解决方案1】:

为您的输入命名并确保它与操作的参数匹配。

<input type="text" id="txt" name="txt" />

[HttpPost]
public ActionResult MyAction(string txt)

【讨论】:

  • 哦,是的!当然!我忘记使用名称...而且我忘记了输入名称必须与我的操作中的参数名称相同。谢谢!
【解决方案2】:

在表单内添加一个输入按钮,以便您提交它

在您的控制器中,您可以通过三种基本方式获取此数据 1.将其作为与你的控件同名的参数获取

公共 ActionResult 索引(字符串文本) { } 或者 公共 ActionResult 索引(FormsCollection 集合) { //当然,将您的输入命名为文本以外的名称:) var 值 = 集合 [“文本”] } 或者 公共 ActionResult 索引(SomeModel 模型) { var yourTextVar = model.FormValue; //假设您的文本框被不恰当地命名为 FormValue }

【讨论】:

    【解决方案3】:

    我通过添加以下代码修改了 Microsoft MVC 研究“电影”应用程序:

    @*Index.cshtml*@
    @using (Html.BeginForm("AddSingleMovie", "Movies"))
    {
        <br />
        <span>please input name of the movie for quick adding: </span>
        <input type="text" id="txt" name="Title" />   
        <input type="submit" />       
    }
    
        //MoviesController.cs
        [HttpPost]
        public ActionResult AddSingleMovie(string Title)
        {
            var movie = new Movie();
            movie.Title = Title;
            movie.ReleaseDate = DateTime.Today;
            movie.Genre = "unknown";
            movie.Price = 3;
            movie.Rating = "PG";
    
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2011-07-25
      相关资源
      最近更新 更多