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

标签 javascript c# jquery ajax asp.net-mvc

问题


我的注册页面上有一个链接,需要调用 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>

这些步骤成功地调用了 Controller 上的方法,但是参数 (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);
    }

所以我需要一种用户点击“发送代码”的方法,该方法停留在同一页面上并调用 Controller 中的 Verify 方法,传递在其上方输入的电子邮件。

最佳答案

您必须传递一个 javascript 对象

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"
 });

关于javascript - MVC C# 将参数传递给 VIA ActionLink 到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159445/

相关文章:

javascript - 在对象中创建动态键

c# - 仅在数组中包含一个数字

c# - lambda 表达式中的枚举的编译方式不同;重载分辨率改进的结果?

javascript - XSD 正则表达式 : empty string OR something else

javascript - 如何增加每个图像的顶部和左侧边距

javascript - 防止重复提交

javascript - 使用 Underscore.js 检查 undefined variable

javascript - D3复合键功能

javascript - 使用 D3 创建 DIV 的动态列表

javascript - MomentJS,UTC时间戳,是问题还是错误?,很少有查询