greatromul
greatromul

Reputation: 1139

Passing input value to action (ASP.Net MVC 3)

I have code in View:

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

How can I pass value of txt to my controller:

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

Upvotes: 16

Views: 68739

Answers (3)

I modified Microsoft MVC study "Movie" app by adding this code:

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

Upvotes: 2

Adam Tuliper
Adam Tuliper

Reputation: 30162

Add an input button inside of your form so you can submit it

<input type=submit />

In your controller you have three basic ways of getting this data 1. Get it as a parameter with the same name of your control

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
}

Upvotes: 10

Brandon
Brandon

Reputation: 70062

Give your input a name and make sure it matches the action's parameter.

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

[HttpPost]
public ActionResult MyAction(string txt)

Upvotes: 48

Related Questions