Подтвердить что ты не робот

Передача входного значения в действие (ASP.Net MVC 3)

У меня есть код в представлении:

@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...
}
4b9b3361

Ответ 1

Дайте вашему вводу имя и убедитесь, что он соответствует параметру действия.

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

[HttpPost]
public ActionResult MyAction(string txt)

Ответ 2

Добавьте кнопку ввода внутри своей формы, чтобы отправить ее

<input type=submit />

В вашем контроллере у вас есть три основных способа получения этих данных 1. Получите его как параметр с тем же именем вашего управления.

public ActionResult Index(string text)
{

}

OR

public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
 var value = collection["text"]
}

OR

public ActionResult Index(SomeModel model)
{
   var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}

Ответ 3

Я изменил приложение Microsoft Movie MVC "Movie", добавив этот код:

@*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");
        }
    }