I’m trying to utilize the MVC3 model validation in my project as of current, however I want to have a simple login section to show in the layout at all times if the user is not logged in. I have the majority of code in place, however the only thing I’m stuck on is how I can post the model back to the form for any validation messages that I produce and need to return.
Normally something like this will work:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel)
{
if(ModelState.IsValid())
{
//Run Further checks & functions
//Upon successful login, retuns to somewhere (Just site index in this example)
return RedirectToAction("Index", "Site");
}
return View(model);
}
Now obviously this won’t work as I can’t return View(model); on the partial unless I just want the login form to be displayed, however I want it to post back to the page that I have been editing from. For example: I navigate to a certain page, contact us, and want to login now. I enter my details on the form that is always available and I enter my details. An error occurs (Incorrect password, incorrect login, account doesn’t exist etc…) and I should be brought back to the contact page with the form still filled in with the details that I entered (except obviously password) with validation summary working etc…
Also, any forms on the page that the layout has rendered still need to work correctly (with models etc)
I’m open to suggestions on how to get this working by other means of submission/return however it would be ideal to have the MVC model validation working.
If anyone needs me to elaborate on anything said, feel free to comment. I’ll be actively responding for a while.
you should create a partial view for login and instead of using “@Html.BeginForm” use @Html.AjaxBegin which submit your page by Ajax call and it RenderHtmlString of login view.
for e.g
after adding “RenderPartialViewToString” method which will return you “RenderHtmlString” of your partial view. you must be pass viewName and Model as parameter to this Method.
in your partail View.
Note: you must be pass UpdateTargetId there your result will Append.