简体   繁体   中英

Generating URL with URL.Action helper and proper encoding of javascript variables

I'm trying to call an action method in ASP.MVC with AJAX using URL generated by Url.Action helper. I have a few arguments which are javascript variables extracted from DOM using jQuery.

I have tried two approaches and both failed.

I've simplified example using only two variables. In real world there's four (decimal?, string, string, string).

First:

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link + '?first=' + first + '&second=' + second;

In this scenario all arguments are passed to the action method but when variable contains some non-standard character (for instance "é") it is malformed and I have problems with restoring proper encoding of it (for instance "Simplifi s" instead of "Simplifiés")

Second:

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name, new { first = "-1", second = "-2"})'

link = link.replace("-1", first);
link = link.replace("-2", second);

In this scenario only first variable (which is nullable decimal) is passed to the action method. The rest are the empty strings.

I've noticed that in the second case the link looks like that:

/ControlerName/Edit?first=890 &amp ;second=Something

(spaces between 890 and ;second are inserted only because of stack overflow's html rendering)

while in the first case it looks as follows:

/ControlerName/Edit?first=890&second=Something

Action method looks like that:

[HttpGet]
public virtual ActionResult Edit(decimal? first, string second)
{
   //code
}

Ajax call looks as follows:

$.ajax({
    url: link,
    type: 'get',
    cache: false,
    async: true,
    success: function (result) {
        $('#someId').html(result);
    }
});

Variables are selected from DOM as follows:

var first = $(this).closest('tr').find('.first').html();

@Url.Action will do necessary encoding for your base url, but you have to handle the url encoding for your 2 javascript variables first and second by yourself.

One straightforward way is to use encodeURIComponent() :

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link 
       + '?first=' + encodeURIComponent(first) 
       + '&second=' + encodeURIComponent(second);

Or as @Nilesh mentioned in comment, you can do it in one time use encodeURI()

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link + '?first=' + first + '&second=' + second;
linkToUse = encodeURI(link);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM