我正在使用 ASP.NET Core 3.1 MVC 创建一个带有表单的页面。该表单有一个下拉列表和一个文本框。下拉列表中填充了数据库中的值。文本框将根据所选的下拉列表值填充同一个表和下拉列表中的值。我的目标是在我的 View 中从我的 Controller 调用一个函数,这可能吗?
我的 cshtml 文件:
<form method="post" asp-controller="Index" asp-action="Index" role="form">
<div class="form-group">
<select id="fileName" asp-items="@(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile()"></select>
<input />
</div>
</form>
我的模型
public class myFiles
{
public int ID {get; set;}
public string fileName {get; set;}
public string uploadedFile {get; set;}
}
我的 Controller 有一个名为 GetUploadedFile() 的函数,它对数据库运行查询,根据 ID 返回文件名。我最初认为我可以通过我的 View (cshtml 文件)通过添加 onchange 处理程序并将其设置为 onchange="GetUploadedFile()"来引用 GetUploadedFile。我还尝试进行 ajax 调用以获取 UploadedFile。
最佳答案
My goal is to call a function from my controller inside of my view, is that possible?
您的意思是要根据 jquery 方法 onchange getUploadedFile 中的下拉列表选择值添加 myfiles 的 uploadfile 值吗?如果这是您的需求,我建议您可以尝试使用ajax 来实现您的需求。
您可以编写 ajax 向 mvc 操作发送请求,然后您可以获取值并将结果设置到文本框。
具体可以引用下面的代码:
<form method="post" asp-controller="home" asp-action="Index" role="form">
<div class="form-group">
<input id="uploadedFile" type="text" class="form-control" />
<select id="fileName" asp-items="@(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile(this)"></select>
</div>
</form>
<script>
function getUploadedFile(Sle) {
$.ajax({
url: "/Home/GetUploadfileName",
data: { "FileID": Sle.value} ,
type: "Post",
dataType: "text",
success: function (data) {
console.log(data);
$("#uploadedFile").val(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
操作方法:
private List<myFiles> myfiletestdata = new List<myFiles>() {
new myFiles(){ ID=1, fileName="test1", uploadedFile="testuploadfile" },
new myFiles(){ ID=2, fileName="test2", uploadedFile="testuploadfile2" },
new myFiles(){ ID=3, fileName="test3", uploadedFile="testuploadfile3" },
};
[HttpPost]
public IActionResult GetUploadfileName(int FileID) {
//get the filename result accoding to ID
var result = myfiletestdata.Where(x=>x.ID== FileID).First();
return Ok(result.uploadedFile);
}
结果:
关于c# - 使用 ASP.NET Core MVC 根据从下拉列表中选择的值填充文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62585325/