'Is it possible to pass a parameter/single form element to a controller via unobtrusive AJAX in ASP.Net Core?
I've got a ASP.Net Core MVC app and I have the need to have certain elements update on a click. For example, a create a person form that searches for an existing address.
I know that I can't use nested forms, However, by going back to my knowledge from MVC 3 days, I thought about unobtrusive Javascript and then running a script from the result to update the main form.
This works great when I mock the controller to retrieve a set value, but, I just can't figure out how to pass a parameter.
For a basic example, my form:
<form>
----
xxxx LOADS OF FORM ELEMENTS xxxx
----
Address:
<input type="text" name="address">
<a href="" data-ajax="true" data-ajax-url="LoadAddress" data-ajax-update="#test" data-ajax-mode="after" data-ajax-complete="changeid">LoadAddress</a>
</form>
Now, on this - by having my controller simply return 1
, it works well... but, I really want to pass the input to the controller first.
Is there anyway to intercept the request and pass the data of the address field, or, should I dump the idea of using unobtrusive AJAX and do something more native?
(and... I am finding so much documentation to be out of date... whilst I am finding it works for other bits, is unobtrusive AJAX still used?)
Solution 1:[1]
You could leave out the form tag and bind your AJAX calls to event listeners. Then you can send and receive values any time you want.
HTML
<input type="text" name="address" id="address">
<button id="submit">submit the form</button>
JS
let field = document.querySelector("#address")
let btn = document.querySelector("#button")
field.addEventListener("change", (e)=> {
fetch(`http://yourapi.com/search?address=${e.target.value}`)
.then(res => {
console.log("search result was returned")
})
})
btn.addEventListener("click", (e)=> {
console.log("use fetch to submit the form here")
})
Solution 2:[2]
You are doing it correctly by setting the name
attribute to the <input>
You should be able to access the value in the controller....
public IActionResult GetAddress(string address){
//do something with address
return View();
}
You can also see this in Pass Parameters through unobtrusive-ajax form.net core
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kokodoko |
Solution 2 | cjadd7 |