1

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?)

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Dev X
  • 89
  • 9

2 Answers2

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")
})
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • This is great, thank you... never used fetch before, but seems interesting... I'm going to keep this open for a bit because I'm still curious if it is possible through unobtrusive (due to model binding/being much simpler for the basics stuff), but, if I get nothing back, I'll happily mark this as the answer. – Dev X Feb 17 '19 at 18:45
0

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

cjadd7
  • 123
  • 1
  • 7