ASP.NET MVC get textbox input value

Ralph picture Ralph · Sep 18, 2013 · Viewed 475.5k times · Source

I have a textbox input and some radio buttons. For example my textbox input HTML looks like that:

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

Once user clicks a button on a web page I want to pass data to my controller:

<input type="button" name="Add" value="@Resource.ButtonTitleAdd"  onclick="location.href='@Url.Action("Add", "Configure", new { ipValue =@[ValueOfTextBox], TypeId = 1 })'"/>

Maybe it is trivial but my problem is that I do not know how to get textbox value and pass it through to the controller. How can I read the textbox value and pass it to the controller through ipValue=@[ValueOfTextBox]?

Answer

Andrei picture Andrei · Sep 18, 2013

Simple ASP.NET MVC subscription form with email textbox would be implemented like that:

Model

The data from the form is mapped to this model

public class SubscribeModel
{
    [Required]
    public string Email { get; set; }
}

View

View name should match controller method name.

@model App.Models.SubscribeModel

@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)
    <button type="submit">Subscribe</button>
}

Controller

Controller is responsible for request processing and returning proper response view.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Subscribe(SubscribeModel model)
    {
        if (ModelState.IsValid)
        {
            //TODO: SubscribeUser(model.Email);
        }

        return View("Index", model);
    }
}

Here is my project structure. Please notice, "Home" views folder matches HomeController name.

ASP.NET MVC structure