Передача входного значения в действие (ASP.Net MVC 3) - PullRequest
16 голосов
/ 11 мая 2011

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

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

Ответы [ 3 ]

46 голосов
/ 11 мая 2011

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

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

[HttpPost]
public ActionResult MyAction(string txt)
10 голосов
/ 11 мая 2011

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

<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
}
2 голосов
/ 19 декабря 2012

Я изменил приложение Microsoft MovC Study "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");
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...