0

In my project (ASP.NET Core 2.2. MVC) I'm trying to do an ajax post with additional parameters to the view model. The form on the page has an id='frmMain'.

My js looks like this:

//post
var data = {
    model: $("#frmMain").serialize(),
    passtest: 'test'
};

$.ajax({
    type: 'post',
    url: url,
    data: JSON.stringify(data),
    dataType: 'json',
    success: function () {
    //alert('form was submitted');
}
}).done(function (result) {

    if (result.status === "success") {

        //some code here
    }
    } else {
        //some code here
    }
});

My controller actions looks like this:

public IActionResult DoSomething(MyModel model, string passtest)
{
    //some action code here
}

Now, the post works, but in my controller action only "model" is filled with data. Variable "passtest" is null. Also there is no "passtest" in the "model".

What am I doing wrong?

Note: I found a workaround with filling hidden fields (and adding them to the view model), but plainly passing multiple parameters in the post itself seems more practical...

1 Answer 1

1

you can append it to the url using the query notation.

url = url + '?passtest=' + myVal

Let's say if your myVal includes special characters like , / ? : @ & = + $ #

You then want to encode it so they are not parsed as part of the url notation:

url = url + '?passtest=' + encodeURIComponent(myVal)

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, this works. Can myVal contain special characters like: ' " / \ ? +
@TheMixy kinda, you'll need to encode the part of the url containing special characters using the encodeURIComponent(part) function. I've updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.