Naresh
Naresh

Reputation: 2673

Accept email id as an action parameter to a controller in MVC3

How can I make my controller action to accept email as a param.

These are the routes I have

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

This is my controller.

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

And this is my view

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

If I am entering values just like normal text the action is being invoked. But if I am trying to enter values like '[email protected]' I am getting '404 not found' error.

Upvotes: 0

Views: 357

Answers (1)

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

how about sending it like this :

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

EDIT :

try surrounding it inside double quotation:

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

Upvotes: 1

Related Questions