问题描述:

I have a Partial view (Login, with username, password and Submit button), and the partial view is being used on my _layout (materpage).

So, on my _layout page, I have:

<div style="text-align: right">

@Html.Partial("_LoginPartial")

</div>

My _LoginPartial has the following code:

 @if (Request.IsAuthenticated)

{

<textarea>Welcome!

[ @Html.ActionLink("Log Off", "Logout", "Account")]</textarea>

}

else

{

@Html.Partial("~/Views/Account/Index.cshtml")

}

The Index file to display the login box looks like this:

 @using GalleryPresentation.Models

@model LoginModel

<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>

@using (Html.BeginForm("index", "Account"))

{

<table>

<tr>

<td>@Html.LabelFor(m => m.Username)</td>

<td>@Html.TextBoxFor(m => m.Username)</td>

</tr>

<tr>

<td>@Html.LabelFor(m => m.Password)</td>

<td>@Html.PasswordFor(m => m.Password) kjkj</td>

</tr>

<tr>

<td colspan="2"><input type="submit" value="Login"/></td>

</tr>

<tr>

<td colspan="2">@Html.ValidationSummary()</td>

</tr>

</table>

}

In my AccountCOntroller, I have the following code:

public ActionResult Index()

{

return View();

}

[HttpPost]

public ActionResult Index(LoginModel loginModel)

{

if(ModelState.IsValid)

{

var g = new GallaryImage();

var user = g.LoginUser(loginModel.Username, loginModel.Password);

if(user != null)

{

FormsAuthentication.SetAuthCookie(user.username, false);

return RedirectToAction("Index", "Home");

}

ModelState.AddModelError("", "Invalid Username/Password");

}

return View(loginModel);

}

public ActionResult Logout()

{

FormsAuthentication.SignOut();

return RedirectToAction("Index", "Home");

}

I have breakpoints on all methods - but they never get hit. Pressing the submit button simply changes my URL to:

http://localhost:8741/?Username=myusername&Password=mypassword

Can anyone spot the error I am making?

网友答案:

Since Html.BeginForm defaults to making GET requests, you are making a GET request with from your view. However, your action only accepts POST requests.

You can change @using (Html.BeginForm("index", "Account")) to @using (Html.BeginForm("index", "Account", FormMethod.Post)).

相关阅读:
Top