[英]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.我有一个 ASP.Net Core MVC 应用程序,我需要通过单击更新某些元素。 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.我知道我不能使用嵌套的 forms,但是,通过回顾我 3 天的 MVC 知识,我想到了不显眼的 Javascript,然后从结果运行脚本来更新主窗体。
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.当我模拟 controller 以检索设置值时,这非常有效,但是,我只是不知道如何传递参数。
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.现在,关于这个 - 通过让我的 controller 简单地返回
1
,它工作得很好......但是,我真的想先将输入传递给 controller。
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?无论如何拦截请求并传递地址字段的数据,或者,我应该放弃使用不显眼的 AJAX 的想法并做一些更原生的事情吗?
(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?) (而且......我发现很多文档都已过时......虽然我发现它适用于其他位,但仍然使用不显眼的 AJAX 吗?)
You could leave out the form tag and bind your AJAX calls to event listeners.您可以省略表单标记并将您的 AJAX 调用绑定到事件侦听器。 Then you can send and receive values any time you want.
然后您可以随时发送和接收值。
HTML HTML
<input type="text" name="address" id="address">
<button id="submit">submit the form</button>
JS 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")
})
You are doing it correctly by setting the name
attribute to the <input>
您通过将
name
属性设置为<input>
来正确地做到这一点
You should be able to access the value in the controller....您应该能够访问 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您还可以在Pass Parameters through unobtrusive-ajax form.net core中看到这一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.