Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax does not work with MVC custom Routing

I have been going through so many forums to get solution but all in vain. My problem is :

I have an action in my home controller named CallUser. I am calling this via ajax.

My URL looks like mydomain.com/Home/CallUser

I want my URL like mydomain.com/CallUser

I do not want to have "/Home" in accessing any of the action

So I added custom routing

routes.MapRoute(
                    "Custom", 
                    "{action}/{id}", 
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );

Ajax call:

function CallUser()
{

    var mobNum = $('#userMobileNo').val();   
    var isValidNumber=validatePhone(mobNum);
    if(isValidNumber)
    {
        $.ajax({
            url: "../Home/CallUser",
            type: "POST",
            data: JSON.stringify({ destinationNumber: mobNum }),
            datatype: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {


            },
            error: function (err) {               

            },
            failure: function(err)
            {              

            }
        });
    }
    else
    {       

    }
}

Call to Blog action in home controller

@Html.ActionLink("Blog", "Blog", "Home")
like image 507
user3678961 Avatar asked Jan 24 '26 22:01

user3678961


1 Answers

Rather than break the standard MVC pattern, just because of a dislike of the URL, just create a UserController and have a Call action so the URL becomes the readable:

"../User/Call"

This then lends itself to URLs like:

"../User/Hangup"
"../User/GiveAbuse"
"../User/Ignore"
"../User/WhyDontTheyEverCall"

Controllers are meant to encompass one part of the problem domain (in this case all actions to do with users), so why fight the MVC way of doing it :)

like image 133
Gone Coding Avatar answered Jan 26 '26 14:01

Gone Coding