This JavaScript code is being used to pass a string from a view to an action in a controller:
<script type="text/javascript">
$(document).on('click', 'a', function () {
$.ajax({
type: 'POST',
url: '/brandsOfACategory',
contentType: 'application/json; charset:utf-8',
data: JSON.stringify(this.id)
})
});
</script>
brandsOfACategory code in the controller:
public ActionResult brandsOfACategory(string id)
{
return View();
}
Code is not working as expected as id is coming as null.
Can someone please guide?
$.ajax({
type: 'POST',
url: '/brandsOfACategory',
contentType: 'application/json; charset:utf-8',
data: { 'id': id }
})
With your current code, when the ajax call is made, the request payload has only a string value. For example, if your clicked link has an Id
attribute value "link1", it will send the below string as the request payload for your ajax call.(You can see this if you open up your dev tools->network tab)
"link1"
For model binding to work, the payload should have a key-value format so that the value will be mapped to the parameter with the same value as the key.
Since it is a simple value, you do not need to necessarily send the JSON stringified version and the contentType
as application/json
. Simply send the JS object as data
. Make sure you are sending a JavaScript object which has the key/property name same as your action method parameter name( id
) and it will work.
Assuming your anchor tag has a valid Id
attribute value so that the this.id
expression returns the valid string value.
<a href="/SomeUrl" id="myId">MyLink</a>
In the script, you probably want to stop the normal click behavior as well to prevent the page from navigating to the href attribute value.
$(document).on('click', 'a', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/brandsOfACategory',
data: { id :this.id }
}).done(function (res) {
console.log('result from ajax call',res);
})
});
This will send the value like id=myId
as the Form Data for the request. Since you are not specifying the contentType explicitly, it will use the default application/x-www-form-urlencoded
If the link user clicked does not have an Id
attribute, the code will send no value because this.id
will return an empty string and your parameter value at server side will be null.
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.