Reputation: 6427
I have a ASP.NET Razor view which binds to string. Its very simple:
@model string
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Hello, @Model
@using(Html.BeginForm())
{
<fieldset>
<label for="name" style="color: whitesmoke">Name:</label>
<input type="text" id="name"/>
<br/>
<input type="submit" value="Submit"/>
</fieldset>
}
And a simple controller:
[HttpGet]
public ActionResult Index()
{
object model = "foo";
return View(model);
}
private string name;
[HttpPost]
public ActionResult Index(string name)
{
return View();
}
When I push the submit button, the Index Post action result triggers, but the 'string name' parameter is null. Isn't Razor smart enough to automatically bind this property to my controller from the view because the input id matches the name of the param on the controller? If not, how do I bind this? I know with a model with properties I can use Html.HiddenFor(m => m.Foo), but since there's no properties, I don't know how to call this method properly.. I can set it properly calling Html.Hidden("name","foo"), but I don't know how to pass a the value here. I know I can use jquery call such as:
@Html.Hidden("name", "$('input[id=name]').val())");
This literally sends the jquery string to the controller as the value... I'm not sure what to do at this point. Thanks!
Upvotes: 3
Views: 6120
Reputation: 13640
It is smart enough to bind the property, just give your input a name which matches with the action parameter:
<input type="text" id="name" name="name" />
Upvotes: 3