开发者

ASP.NET MVC - Navigation Approach

I am new to ASP.MVC. My background is in ASP.NET Web Forms, I think this is what is causing my confusion. I understand that the "M" basically represents the data source, the "V" represents the resource I'm requesting and the "C" dictates what gets shown to an end-user. But then I get confused.

For instance, I'm just trying to create a Login screen. I envision a user visiting "http://www.myapp.com/Account/Login" and they will be presented with a traditional Login screen. To accomplish this, I have added the following in the RegisterRoutes method in my Global.asax file:

routes.MapRoute(
  "Login",
  "{controller}/{action}",
  new { controller = "Account", action = "Login", id = "" }
);

The Login action executes, but this is where I get confused. You see, the first time the login screen loads, I would expect to just show a username/password field. Then on post, I would expect the form to be validated and processed. In an attempt to do this, I have created the following method:

public ActionResult Login()
{
  bool isFormValid = ValidateForm();
  if (isFormValid)
    LoginUser();
  else
    ShowErrors();

  return View();
}

My confusion rests with the Login action. Initially, there is no data. But the next time, I want to validate the dat开发者_StackOverflowa. How do I determine if the Action is a postback or not?

Thank you!


The easiest way to handle this is with two actions: one for get, one for post. Use the AcceptVerbs attribute to control which gets invoked depending on the method. BTW, the default routes should work just fine for this case since when the controller and action is supplied it gets directed as you would expect. I thought that this scenario was also covered in the project template -- did you set up a project using the template or an empty one?

[AcceptVerbs( HttpVerbs.Get )]
public ActionResult Login()
{
}

[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Login( string userName, string password )
{
}


You need two different methods, for Post and Get.

[AcceptVerbs (HttpVerbs.Get]
public ActionResult Login ()
{
    return View ();
}

[AcceptVerbs (HttpVerbs.Post]
public ActionResult Login (FormCollection form)
{
    if (AuthenticationSuccess ())
        return RedirectToAction ("Account");
    else
        return View ();
}

For Post version you can use the model binding mechanism:

public ActionResult Login (LoginModel loginModel)

Or

public ActionResult Login (string LoginName, string Password)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜