C# 如果在提交时选中了另一个单选按钮,则返回视图时将不记得该复选框

C# 如果在提交时选中了另一个单选按钮,则返回视图时将不记得该复选框,c#,asp.net-mvc,C#,Asp.net Mvc,默认情况下,我选择了一个,但当我选中另一个时,从控制器返回时,它应该仍然选中该选项。正如您在问题中首先提到的,您需要创建viewModel。例如: @Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "Id") <text> ID &nbsp &nbsp</text> @Html.RadioButtonFor(model => model.EditSearchVM.Search

默认情况下,我选择了一个,但当我选中另一个时,从控制器返回时,它应该仍然选中该选项。

正如您在问题中首先提到的,您需要创建viewModel。例如:

@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "Id") <text> ID  &nbsp &nbsp</text>
@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "CreationDate", new { @checked = "checked" }) <text> Creation Date  &nbsp &nbsp</text><br />
为了保持示例的简单性,我将使用Home controller和Index。在视图中,您需要创建一个HTML表单并将数据传递给视图

public class EditSearchVM
{
    public string SearchBy { get; set; }
    //Some other properties ....
}
然后你需要后期动作。如果要在返回页面时保持当前选中状态,还需要传递模型。因此,您的后期操作如下所示:

public IActionResult Index()
{
     //Set the default selected
     var model =  new EditSearchVM (){ SearchBy = "CreationDate" };            
     return View(model);
}

您需要比较控制器代码中哪些工作正常,哪些不工作,并找出区别。你有密码,所以我们甚至猜不出问题出在哪里。猜测是,在将模型发送回视图之前,您正在重置模型的属性值。我已经调试了它,当它到达视图时,该值是正确的
public IActionResult Index()
{
     //Set the default selected
     var model =  new EditSearchVM (){ SearchBy = "CreationDate" };            
     return View(model);
}
[HttpPost]
public IActionResult Index(EditSearchVM model)
{
    if (ModelState.IsValid)
    {
        //Do something and redirect to proper controller and action
    }
    return View(model);
}