首页 > 解决方案 > 如何通过单击 ASP.Net Core MVC 中的单选按钮从模型中获取选择性数据?

问题描述

场景背景: 1. 两个单选按钮 - “默认”“首选” 2. 一个文本框 - “DirPath”(根据单选显示默认/首选路径) 3. 在模型类内部,有两个类成员(字符串DefPPrefP - 保存默认/首选路径)并在第一次执行 MVC 操作时通过读取一些数据库(考虑注册表)进行初始化。

要求: 1. 当“默认”单选按钮被按下时,“DirPath”应该获取最新的 DefPPrefP不应该被获取(虽然它没有被显示) 2.同样,当“首选”单选按钮被按下时,“DirPath”应该获取最新的 PrefPDefP不应该被获取(虽然它没有被显示)。3.视图(UI)不应重新加载。

原因:将数据的获取限制在所需的范围内。

标签: asp.net-mvcasp.net-coretextboxradio-buttonfetching-strategy

解决方案


您可以尝试使用 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>
}

推荐阅读