How do I encapsulate form/post/validation[/redirect] in ViewUserControl in ASP.Net MVC 2
- by paul
What I am trying to achieve:
encapsulate a Login (or any) Form to be reused across site
post to self
when Login/validation fails, show original page with Validation Summary
(some might argue to just post to Login Page and show Validation Summary there; if what I'm trying to achieve isn't possible, I will just go that route)
when Login succeeds, redirect to /App/Home/Index
also, want to:
stick to PRG principles
avoid ajax
keep Login Form (UserController.Login()) as encapsulated as possible; avoid having to implement HomeController.Login() since the Login Form might appear elsewhere
All but the redirect works. My approach thus far has been:
Home/Index includes Login Form: <%Html.RenderAction("Login","User");%>
User/Login ViewUserControl<UserLoginViewModel> includes:
<%=Html.ValidationSummary("") %
using(Html.BeginForm()){}
includes hidden form field "userlogin"="1"
public class UserController : BaseController {
...
[AcceptPostWhenFieldExists(FieldName = "userlogin")]
public ActionResult Login(UserLoginViewModel model, FormCollection form){
if (ModelState.IsValid) {
if(checkUserCredentials()) {
setUserCredentials()
return this.RedirectToAction<Areas.App.Controllers.HomeController>(x = x.Index());
}
else {
return View();
}
}
...
}
Works great when: ModelState or User Credentials fail -- return View() does yield to Home/Index and displays appropriate validation summary.
(I have a Register Form on the same page, using the same structure. Each form's validation summary only shows when that form is submitted.)
Fails when: ModelState and User Credentials valid -- RedirectToAction<>() gives following error:
"Child actions are not allowed to perform redirect actions."
It seems like in the Classic ASP days, this would've been solved with Response.Buffer=True. Is there an equivalent setting or workaround now?
Btw, running: ASP.Net 4, MVC 2, VS 2010, Dev/Debugging Web Server
I hope all of that makes sense.
So, what are my options? Or where am I going wrong in my approach? tia!