MadDev
MadDev

Reputation: 1150

How to pass textbox values to MVC Action?

I have tried the below but I get the compliation error:

The name 'txtMakeModelTypeCode' does not exist in the current context.

<label>Type Code</label>
<input type="text" id="txtMakeModelTypeCode" name="txtMakeModelTypeCode" />
<label>Make</label>
<input type="text" id="txtMake" name="txtMake"/>
<label>Model</label>
<input type="text" id="txtModel" name="txtModel"/>
<a href="@Url.Action("CreateMakeModel", "Vehicle", new { MakeModelTypeCode = txtMakeModelTypeCode, make = txtMake, model = txtModel })">Create</a>

I have also tried using a form but I don't want to use a submit button. Is it possible to use a plain button?

@using (Html.BeginForm("CreateMakeModel", "Vehicle"))
{
  <label>Type Code</label>
  @Html.TextBox("txtMakeModelTypeCode")
  <label>Make</label>
  @Html.TextBox("txtMake")
  <label>Model</label>
  @Html.TextBox("txtModel")
  <input type="submit" value="Create" />
}

Upvotes: 0

Views: 322

Answers (1)

Steve Harris
Steve Harris

Reputation: 5109

MVC does not work the same as ASP.Net Webforms. The textboxes you create are not available in code. You use the controls to render your html and handling of data is done via the model.

So use TextBoxFor:

@using (Html.BeginForm("CreateMakeModel", "Vehicle"))
{
    <label>Type Code</label>
    @Html.TextBoxFor(m => m.MakeModelTypeCode)
    <label>Make</label>
    @Html.TextBoxFor(m => m.Make)
    <label>Model</label>
    @Html.TextBoxFor(m => m.Model)
    <input type="submit" value="Create" />
}

Then in your controller, after the post, you should have the posted data in the model:

public ActionResult Index(CreateMakeModel model) // or is it Vehicle?
{
    // whatever you do here:
    string code = model.MakeModelTypeCode;
}

Upvotes: 2

Related Questions