![](/img/trans.png)
[英]Window.location.href post parameters to actionresult asp.net mvc
[英]ASP.NET MVC ActionResult POST without Submit
所以我是一個非常新的ASP.NET MVC,幾個月前和幾個月前我都介紹了ASP.NET,但不幸的是,幾乎忘記了所有事情:(
我已獲得一項向頁面添加查找按鈕的任務,該頁面從文本框中輸入用戶名並驗證該用戶名是否有效。
我花了很多小時試圖使它工作。 不幸的是,我真正需要做的是坐下來幾個星期,重新自學,學習javascript,jquery,asp.net mvc。 我將學習所有這些內容,但是這項任務規模很小,具體花費了數周的時間來學習語言和框架以開始解決。
這是我的位置:
控制器結構:
public class NewUserRequestController : Controller
{
// GET: NewUserRequest
public ActionResult Index()
{
return View(new NewUserRequest());
}
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult LookupLDN(ITFormsLibrary.NewUserRequest req)
{
//Code that Verifies user etc
return View(req);
}
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Submit(ITFormsLibrary.NewUserRequest req)
{
//Code that handles submission validation & errorvalidation
return View("Index", req);
}
}
現在,在視圖中,我嘗試弄亂:
@using((Ajax.BeginForm("LookupLDN", "NewUserRequest", FormMethod.Post, new AjaxOptions { UpdateTargetId = "NewUserIfo"}, new { @class = "form-inline", role = "form" }))
只是發現我不能嵌套表格。
我努力了:
@Ajax.ActionLink("Lookup", "LookupLDN", "NewUserRequest", new { Model},null, new { @class = "form-inline", role = "form" })
和
@HTML.ActionLink("Lookup", "LookupLDN", "NewUserRequest", new { Model})
由於某種原因,兩者都返回404。
我也嘗試過:
<input type="button" value="Lookup" onclick="return lookupLDN()"/>
但是,我不知道如何構造一個JavaScript語句來處理異步POST? -我什至要發布嗎?
如果你們中的任何人理解我正在努力實現的目標並可以提供幫助,我將非常感謝。 謝謝!
JSON怎么樣。
根據湯米的評論進行 編輯 。 使用POST而不是GET。
它應該是一種POST方法,因為您是在向服務器發送數據並要求其對該數據采取行動(POST),而不僅僅是要求服務器向我們提供信息而不發送任何信息(GET)。 使用POST,您可以在CSRF令牌周圍添加檢查,而不必擔心Googlebot會執行不應執行的操作,等等。
HTML(查看)
<input type="button" id="btnLookupUser" value="Lookup" />
JAVASCRIPT
$(document).ready(function () {
$('#btnLookupUser').click(function () {
var vUsername= $('#txtUserName').val();
if (vUsername.trim() == '') {
return;
}
else
{
//URL to your JSON method. (here I suppose you have a LookupUser action method. Change application path the way it works for you.)
$.ajax({
url: applicationPath + '/LookupUser',
type: 'POST',
dataType: 'json',
data: { userName: encodeURIComponent(vUsername.trim()),
cache: false,
success: function (result) {
//Do your logic based on the result.
switch (result) {
case true:
break;
default:
break;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
})
});
});
CONTROLLER
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LookupUser(string userName)
{
//Your logic
return Json("Whether is valid or not"); //You can as well deny GET here.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.