Reputation: 1477
I have a View that is returned by and action Method from a controller like this:
public ActionResult Create()
{
return View()
}
[HttpPost]
public ActionResult Create(FormCollection form)
{
}
I want them to be done in a single View like So:
@model Models.RegistrationViewModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
@Html.TextboxFor(model.User.Username )
}
but the problem is i cant bind my textboxfor to the models Properties.. How can i consume a single view for post and get in my scenario..
Upvotes: 1
Views: 16398
Reputation:
You usage of @Html.Textbox(model.User.Username)
means that you generating a textbox with a name
attribute equal to the value Username
which would not bind to a model. If the value of UserName
where say John
it would generate
<input type="text" name="John" id="John" value />
Change it to
@Html.TextBoxFor(m => m.User.Username)
which will generate the correct name
attribute which relates to you model
<input type="text" name="User.Username" id="User_Username" value="John" />
Then change the POST method signature to
[HttpPost]
public ActionResult Create(RegistrationViewModel model)
so that the model is bound and its values correctly set.
Note also the method is named Create()
so in your view it needs to be
@using (Html.BeginForm("Create", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })
Upvotes: 5
Reputation: 1503
The action in the Beginform should be the same name as the action method:
also, pass the model to the action method:
[HttpPost]
public ActionResult Create(RegistrationViewModel pMyModel)
{
string tUsername= pMyModel.User.Username;
}
also you need a submit button inside the form to apply the post action:
@model Models.RegistrationViewModel
@using (Html.BeginForm("Create", "Account", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
@Html.TextboxFor(m => m.model.User.Username )
<input value="create" type="submit"/>
}
Upvotes: 3