asp.net-mvc - 如何通过单击 ASP.Net Core MVC 中的单选按钮从模型中获取选择性数据?
问题描述
场景背景: 1. 两个单选按钮 - “默认”和“首选” 2. 一个文本框 - “DirPath”(根据单选显示默认/首选路径) 3. 在模型类内部,有两个类成员(字符串DefP,PrefP - 保存默认/首选路径)并在第一次执行 MVC 操作时通过读取一些数据库(考虑注册表)进行初始化。
要求: 1. 当“默认”单选按钮被按下时,“DirPath”应该获取最新的 DefP而PrefP不应该被获取(虽然它没有被显示) 2.同样,当“首选”单选按钮被按下时,“DirPath”应该获取最新的 PrefP和DefP不应该被获取(虽然它没有被显示)。3.视图(UI)不应重新加载。
原因:将数据的获取限制在所需的范围内。
解决方案
您可以尝试使用 javascript 来设置DirPath
基于单选按钮单击事件的值。
这是一个简单的例子
模型
public class TestModel
{
public string DefP { get; set; }
public string PrefP { get; set; }
}
控制器
public IActionResult Test()
{
var model = new TestModel
{
DefP = "defPath",
PrefP = "prefPath"
};
return View(model);
}
看法
@model MVCTest2_2.Models.TestModel
<input type="radio" id="default" name="default" />Default
<input type="radio" id="preferred" name="preferred" />Preferred
<br />
<label>DirPath</label>
<input type="text" id="dirPath" name="dirPath"/>
@section Scripts
{
<script>
$(document).ready(function () {
$("#default").change(function () {
if ($('input[name=default]').is(':checked')) {
$("#dirPath").val('@Model.DefP');
$("#preferred").prop("checked", false);
}
});
$("#preferred").change(function () {
if ($('input[name=preferred]').is(':checked'))
{
$("#dirPath").val('@Model.PrefP');
$("#default").prop("checked", false);
}
});
});
</script>
}
推荐阅读
- arrays - 数组 Bash/Shell 中的分隔符
- java - 计数器和 for 循环的问题。协助赞赏
- java - 为管理员而不是 Firebase 用户显示按钮是否正确?
- sql - 这怎么能翻译成postgresql?
- r - R - 将一列分成两个相关的
- bash - 如何读取 JIRA REST API 的响应
- telerik - 如何在客户端更新/设置 Telerik RadMaskedTextBox 的掩码(使用 javascript / jquery)
- flask-socketio - FlaskSocketIO 检索所有已连接客户端的列表
- r - 尝试用相同的键替换 aa 列的 na 值,但其中一行有值
- c++ - MPI 和移动语义