Post Data Getting Lost during Ajax Post Request in

2019-09-02 20:45发布

问题:

I am working on an ASP.net MVC 3.0 Application with razor view engine.

I am making an ajax post as follows:

 $.ajax({
       type: "post",                                                                  contentType: "application/json;charset=utf-8",
       url: GetErrorCountUrl,
         success: function (data) {
           });

Here, the URL is as follows:

var GetErrorCountUrl = '@Url.Action("GetErrorCount", "WError", new { Id= "Token", id1 = "Token1", id2= "Token2" })';
GetErrorCountUrl = GetErrorCountUrl.replace('Token',pkid).replace('Token1',cid).replace('Token2',itemclass);

I am building the correct URL . I checked by using alert(url). It is hitting that controller action.

In my controller action,

If i do : Request.params["Id"] --> I was getting the correct value

         Reuqest.params["id1"] --> I am getting null values

but, when i do:

       reuqest.Params[0] --> correct value

       request.params[1]  ---> Correct value

I was getting correct values when using index instead of name.

I need get those values based on Parameter name not on index.

Please help.

Except for the first parameter..i was not able to get the values of other parameters

回答1:

First of all the name of variabeles should start with low letter in JavaScript. Names with the first capital variable should be used only for classes (functions used in constructors). Prettify formatting of the code used on stackoverflow uses other colors for JavaScript classes. For example to define data in JavaScript one should use var d = new Date(); instead of var d = new Date();. So the code like var GetErrorCountUrl = "some string"; looks in JavaScript very strange. I understand that JavaScript is not your main language, but it's really better the name conversion used in the language which one uses.

Now back to your main question. It seems to me that

GetErrorCountUrl.replace('Token',pkid).replace('Token1',cid).replace('Token2',itemclass);

Isn't what you really want. If the string GetErrorCountUrl contains 'Token1' then the 'Token' part of the substring 'Token1' will be first replaced to pkid and the next replacement (to cid) will never work.

To fix the problem you can change the order or replacements to the following for example:

GetErrorCountUrl.replace('Token1',cid)
    .replace('Token2',itemclass)
    .replace('Token',pkid);