MR.ABC
MR.ABC

Reputation: 4862

AngularJS empty input model after mvc postback

Using AngularJS with ng-model all my fields are cleared after postback from mvc controllers. Can prevent this somehow and put the values from the postback into the model? Every time the user make a postback with an validation error all fields get cleared because of the ng-model. Any ideas?

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.TextBoxFor(x => x.Register.Username, new { @ng_model = "username" })
    @Html.TextBoxFor(x => x.Register.Password, new { @ng_model = "password" })
}

[AllowAnonymous]
public ActionResult Register(RegisterModel viewModel)
{
   return View(viewModel);
}

Upvotes: 0

Views: 617

Answers (1)

Chintana Meegamarachchi
Chintana Meegamarachchi

Reputation: 1820

This happens because when Angular kicks in, values for username and password on $scope are null and they would override what is set by your view.

ng-init may solve your problem

consider something like

@Html.TextBoxFor(x => x.Register.Username, new { @ng_model = "username", @ng_init = "username ='" + Model.Register.Username + "'" })
@Html.TextBoxFor(x => x.Register.Password, new { @ng_model = "password", @ng_init = "password ='" + Model.Register.Password + "'" })

Cheers

Upvotes: 5

Related Questions