user516883
user516883

Reputation: 9378

Passing URL in parameters MVC 4

I have a site that collects URLs. A full HTTP URL is entered into a textbox. I am getting a 400 error when a URL is being passed in the parameter. It works fine with regular text.

Using jQuery, how can I pass the full URL in my application?

MVC Routing Config:

 routes.MapRoute("UploadLinks", "media/upload_links/{link}/{albumID}",
                       new { controller = "Media", action = "WebLinkUpload" });

Controller Action:

 public ActionResult WebLinkUpload(string link, string albumID){}

jQuery AJAX call:

$('#btnUploadWebUpload').click(function () {
        $.ajax({
            type: "GET",
            url: "/media/upload_links/" + encodeURIComponent($('#txtWebUrl').val().trim()) + "/" + currentAlbumID,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {

            }
        });
    });

Upvotes: 0

Views: 2067

Answers (2)

Jeffrey Lott
Jeffrey Lott

Reputation: 7409

Make sure that your map route call comes before the default. If it doesn't, it would try calling a media controller with a upload_links action.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Certain characters are not allowed in the path portion of the url. Here's a nice article in which Scott Hanselman gives more details. I would recommend you passing the link as query string parameter and not as part of the route:

routes.MapRoute(
    "UploadLinks", 
    "media/upload_links/{albumID}",
    new { controller = "Media", action = "WebLinkUpload" }
);

and then:

$('#btnUploadWebUpload').click(function () {
    $.ajax({
        type: 'GET',
        url: '/media/upload_links/' + currentAlbumID,
        data: { link: $('#txtWebUrl').val().trim() },
        success: function (result) {

        }
    });
});

Also notice that I have removed the contentType: 'application/json' from the AJAX call which is wrong. You are not sending any JSON request. It's a GET request.

Upvotes: 2

Related Questions