問題描述
如何:(jQuery) 帶有 ASP.NET MVC 2 的模態登錄對話框? (How to: (jQuery) Modal login dialog w/ ASP.NET MVC 2?)
在 ASP.NET MVC 2 中覆蓋內置登錄機制的最佳方法是什麼,以便在用戶需要登錄時彈出模式對話框(或 [Authorize] 標記裝飾控制器操作)?
< p>我已經搜索了一段時間,但沒有什麼真正做到這一點任何幫助或指導將不勝感激
jQuery 不是先決條件,但我熟悉它
參考解法
方法 1:
It's quite possible and not too hard.
This is from another post that I can't seem to find any more:
Yes, it's possible. Just submit the login‑form using the method described here by mike bosch and return a json datastructure with the returnUrl if any.
I have created a lightweight LoginResultDTO class that i return as json:
public class LoginResultDTO
{
public bool Success {get;set;}
public string Message {get;set;}
public string ReturnUrl {get;set;}
}
Here's a script block from my LogOn view:
<script type="text/javascript">
$(document).ready(function() {
var form = $($("form")[0]);
form.submit(function() {
var data = form.serialize();
$.post(form.attr("action"), data, function(result, status) {
if (result.Success && result.ReturnUrl) {
location.href = result.ReturnUrl;
} else {
alert(result.Message);
}
}, "json");
return false;
});
});
</script>
This will ajax wrap the logon form. Note that this is the simplest implementation of the javascript code possible but it's a place to start.
Then I have modified my LogOn action in the AccountController and in the relevant places put something like this:
if(Request.IsAjaxRequest())
{
return Json(new LoginResultDTO{Success=true,Message="Successfully logged in"});
}else
{
return View();
}
So this is an ultralight but rather complete version of how jquery authentication could be done in asp.net mvc.
方法 2:
You can expose a web service in your project that will validate if the user is logged in. On $(document).ready()
do an $.ajax()
call to the web service. Based on the result you can display the modal popup using the $.dialog()
function in the UI library for JQuery.
(by Jerrold、rboarman、Achilles)