繁体   English   中英

MVC C#将参数传递给VIA ActionLink到Controller

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM