views:

728

answers:

2

I have an ASP.NET MVC 2 web site in which I'd like to place login controls in the master page. I want any validation error messages to appear in the master page as well. How would I go about doing this? If I do something like this:

<% using (Html.BeginForm("LogOn", "Account", FormMethod.Post))  {  %>

  <%= Html.LabelFor(d => d.UserName)%>:
  <%= Html.EditorFor(d => d.UserName)%>

  <%= Html.LabelFor(d => d.Password)%>:
  <%= Html.Password("Password")%>

  <input type="submit" value="Login" />

  <%= Html.ValidationSummary() %>

<% } %>

...the account controller method gets called just fine. However, when I return View() from the method, I get an error that no view called "LogOn" exists. How do I achieve my intended result.

+1  A: 

When you call the LogOn action, along with username and password you could pass it a return url to which it will redirect upon successful login instead of returning a view.

Darin Dimitrov
Do you mean you return `Redirect(returnUrl)` in the method? Although that takes me to the right page, it loses the ModelState including validation error messages.
Jacob
Put any state you want into `TempData` and redirect.
Darin Dimitrov
I'll keep this in mind. It should work but kind of seems like a workaround. I'm going to wait to see if somebody has a solution that feels more natural within the MVC framework before accepting the answer.
Jacob
I decided to go with the TempData suggestion. Oh well.
Jacob
A: 

I hate to ask the obvious, but it's unclear from your post: do you actually have a "LogOn" view under the "Account" folder in "Views"?

If you simply return View() from an action, it will look for a view with the same name as the action (in this case "LogOn")

hmm... you can just simply return any View from the login controller: How are you going to get the ViewModel to pass on to that view?etc

At best you can get the refferal URL from the request.. then determine the controller/action from that and return a RedirectAction().. but this time with the model errors incorporated.

Two more things I can think of:

  1. Incorporate your User-Login-Control into an iframe. you'll need to gprade your partial view to a full view.

  2. Use a jQuery

    $.get(url,null, function(result) { $(loginDiv).html(result);
    });

to send the login action, then from the login controller return PartialView("LogOn");

Either way you have a partial page submition and the rest of the content on the page will be unchanged.

Radu094
I don't want to go to a LogOn view. I get an error if it doesn't exist once I return `View()`. If I create the view, then I'm taken to that page. I want it to return to the original page with validation errors if any.
Jacob
Thanks for the additional suggestions.
Jacob