[英]MVC C# Pass parameter to VIA ActionLink to Controller
我的Register頁面上有一個鏈接,需要在Controller中調用一個發送代碼的方法。 當用戶完成表單后,他們單擊“提交”,您可以檢查代碼是否匹配並注冊用戶。
我遇到的問題是當用戶點擊發送代碼鏈接時,我需要將已輸入的電子郵件作為參數傳遞,我似乎無法做到。
以下是我的ActionLink的設置方法:
<%: Html.ActionLink("Send verification code", "Verify", new { id = "codeLink" })%>
此ActionLink對Controller中的方法進行Javascript AJAX調用以停止刷新頁面。 變量'email'被填充,因為我已經調試並測試了它。
$("#codeLink").click(function (e) {
e.preventDefault();
var dataToPost = "{ email:'" + email + "'}";
$.ajax({
url: $(this).attr("href"),
data: dataToPost,
type: "POST",
dataType: 'json',
cache: false,
contentType: "application/jsonrequest; charset=utf-8"
});
});
設置電子郵箱的方式如下:
<p>
<%:Html.Label(Resources.UserEmailAddress)%>
<%:Html.TextBoxFor(m => m.uEmail, new { id = "uEmail" }) %>
<%:Html.ValidationMessageFor(m => m.uEmail) %>
</p>
這些步驟成功調用控制器上的方法,但參數( JSON )未通過。
public void Verify(string email)
{
var VerificationCode = Guid.NewGuid().ToString();
VerificationCode = VerificationCode.Substring(VerificationCode.IndexOf("-") + 1, 4);
Session["VerificationCode"] = VerificationCode;
var emailUsername = new EmailValidationCode();
emailUsername.SendEmail(email, VerificationCode);
}
因此,我需要一種用戶單擊“發送代碼”的方法,該代碼保留在同一頁面上並調用控制器中的驗證方法,並傳遞在其上方輸入的電子郵件。
你必須傳遞一個javascript object
。
var dataToPost = { email:email};
$.ajax({
url: $(this).attr("href"),
data: dataToPost,
type: "POST",
dataType: 'json',
cache: false
});
此外, contentType
是您要發送的數據類型,因此application/json
; 默認為application / x-www-form-urlencoded; 字符集= UTF-8。
如果使用application/json
,則必須使用JSON.stringify()
才能發送JSON object
。
JSON.stringify()
將javascript對象轉換為json文本並將其存儲在字符串中。
var dataToPost = { email:email};
$.ajax({
url: $(this).attr("href"),
data: JSON.stringify(dataToPost),
type: "POST",
dataType: 'json',
cache: false,
contentType: "application/json; charset=utf-8"
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.