将电子邮件ID作为动作参数接受到MVC3中的控制器

时间:2012-11-13 18:50:44

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-mvc-routing

如何让我的控制器操作接受电子邮件作为参数。

这些是我的路线

routes.MapRoute(
                name: "infoNewsletterSignup",
                url: "info/SubscribeToNewsLetter/{email}",
                defaults: new { controller = "Info", action = "SubscribeToNewsLetter", email =UrlParameter.Optional});

            routes.MapRoute(
              name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Info", action = "Index", id = UrlParameter.Optional }
            );

这是我的控制器。

[HttpPost]
public string SubscribeToNewsLetter(string email)
{
   return "Thanks!\n\nYou have successfully subscribed for our newsletter.";
}

这是我的观点

<td>
<input type="text" class="text-bx-foot" value="" id='newsLetterEmail' name='newsLetterEmail'></td>
<td>
<input name="Go" type="button" class="go-btn" value="Go" id="btnSubscribeToNewsLetters"></td>

$(document).ready(function () {
$("#btnSubscribeToNewsLetters").click(subscribeToNewsLetters);
});

function subscribeToNewsLetters() {
var objInputEmail = $("#newsLetterEmail");
if (objInputEmail != null) {
    var id = objInputEmail.val();
    if (id != null) {
        $.ajax({
            type: 'POST',
            url: '/Info/SubscribeToNewsLetter/' + id,
            //data: $('#form').serialize(),
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: subscribed,
            error: errorInSubscribing
        });
    }
}
}

function subscribed(data, textStatus, xhr) {
alert(data);
}

function errorInSubscribing(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}

如果我像普通文本一样输入值,则会调用该操作。但如果我想输入'myname@test.co.uk'这样的值,我会收到'404 not found'错误。

1 个答案:

答案 0 :(得分:1)

如何发送它:

 $.ajax({
                type: 'POST',
                url: '/Info/SubscribeToNewsLetter',
                data: {"email" : Id },
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: subscribed,
                error: errorInSubscribing
            });

编辑:

尝试在双引号中包围它:

 $.ajax({
                type: 'POST',
                url: '/Info/SubscribeToNewsLetter',
                 data: '{"email" : "' + Id + '"}',
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: subscribed,
                error: errorInSubscribing
            });