简体   繁体   中英

How can i pass a parameters to action method using javascript fetch?

I'm using js fetch to call to an action method(in asp.net mvc), but I need to pass parameters to the method.

How can I pass this data using fetch ?

I'm trying to use this code but the data didn't pass:

fetch(url, {
    data: { repositoryName: "dada" }
})
.then(() => {
   console.log("test");
});

According to the documentation second parameter shouldn't contain data property.

I guess you need to use body property(you can use JSON string, FormData or URLSearchParams here basing on your needs, see docs ):

fetch(url, {
    method: "POST",
    body: JSON.stringify({ repositoryName: "dada" })        
}).then(() => { ... })

Also in this simple example it's possible to simply use query string like this:

fetch(url + '?repositoryName=dada').then(() => { ... })

Note that GET requests cannot have body so if your MVC action is GET action then you have to use query strings like in my second example.

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