首页 > 解决方案 > 如何设置默认选中的单选按钮

问题描述

我正在实施 asp.net core 3.1。我的剃刀视图中有三个单选按钮,使用以下代码,我想将选定的单选按钮值发送到控制器中的索引操作,以显示其相关数据。我的问题是,我无法将其中一个单选按钮设置为默认选中。

@model CSD.ChartObjects
 <form method="post">
        @foreach (var year in Model.Years)
        {
            <input type="radio" asp-for="Year" value="@year" />@year<br />
        }
        <input type="submit" asp-action="Index" />
    </form>

这是我在剃刀中读取的模型对象

public class ChartObjects
    {
        public List<ChartModel> Percent { get; set; }
        public List<ChartModel> Time { get; set; }
        public List<ChartModel> Avg { get; set; }
        public List<ChartModel> Total { get; set; }


        public string Year { get; set; }
        public string[] Years = new[] { "1398", "1399", "1400" };
    
}

这是我的 HomeController 的主体:

[HttpGet]
        public IActionResult Index()
        {
            return (BuildIndexModel("1399"));
        }

        [HttpPost]
        public IActionResult Index([FromForm] string currentYear)
        {
            return (BuildIndexModel(currentYear));
        }



        public IActionResult BuildIndexModel(string currentYear)
        {
...
}

标签: asp.net-core-mvc

解决方案


我不知道如何使用 asp.net,但是在 JS 中,我只需要访问 HTML Input 标签的属性,然后您就可以将属性“checked”分配为 true。

我想是这样的:

HtmlElement Input1 = webBrowser1.Document.GetElementById("ID"); // consider adding an ID
Input1.Attributes.Add("checked", "true");

检查这两个链接:


推荐阅读