在Html上设置选定值.从模式asp.net mvc下拉列表



我不能根据我选择的系统在下拉菜单中设置选定值。我尝试了我看到的其他解决方案,但仍然不能解决我的问题。

这是我的代码。

[Serializable]
public class IssuesModel
{
public int ISSUE_ID {get; set;}
public string SYSTEMNAME {get; set;}
public string ISSUE_DESC {get; set;}
.......
}
[Serializable]
public class IssueDetailViewModel
{
public IssuesModel Issue {get; set}
public ICollection<SystemSummaryViewModel> Systems {get; set;} = new List<SystemSummaryViewModel>();
public SelectedSystemModel SelectedSystem {get; set;}
}
[Serializable]
public class SystemSummaryViewModel
{
public int ID {get; set;}
public string SYSTEMNAME {get; set;}
}
[Serializable]
public class SelectedSystemModel
{
public string SYSTEMNAME {get; set;}
}

控制器

[HttpGet]
public ActionResult EditIssue(int id = 0)
{
var selectedIssue = db.TBL_ISSUES
.Where(x => x.ISSUE_ID == id)
.Select(x => new IssueModel
{
ISSUE_DESC = x.ISSUE_DESC,
SYSTEMNAME = x.SYSTEMNAME
......
}).FirstOrDefault();
var systems = db.LIB_SYSTEMS
.Where(x => x.ENABLED == "Y")
.Select(x => new SystemSummaryViewModel
{
ID = x.ID,
SYSTEMNAME = x.SYSTEMNAME
}).ToList();
var selectedSystem = db.TBL_ISSUES
.Where(x = x.ISSUE_ID == id)
.Select(x => new SelectedSystemModel
{
SYSTEMNAME = x.SYSTEMNAME
}).FirstOrDefault();
var model = new IssueDetailViewModel
{
Issue = selectedIssue,
Systems = systems,
SelectedSystem = selectedSystem
}
};
return View(model);
<<p>视图/strong>
@model ProjectName.Models.IssueDetailViewModle
@{
Layout = null;
}
....
<div class="form-group">
@{
var systemList = new List<SelectedListItem>();
foreach(var item in Model.Systems)
{
systemList.Add(new SelectListItem() { Text = item.SYSTEMNAME, Value = item.SYSTEMNAME}); //this is my current in populating dropdown values
}
}
@Html.DropDownListFor(m => m.SelectedSystem.SYSTEMNAME, systemList, new { @class="control-label"})
//also tried below but no luck
@*
Html.DropDownListFor(m => m.SelectedSystem.SYSTEMNAME, new SelectList(Model.Systems, "SYSTEMNAME", "SYSTEMNAME", Model.SelectedSystem), "Select System", new { @class ="form-control"}
*@
</div>

我只得到下拉列表,但没有默认选择的项目。希望你能帮我。非常感谢,祝你今天愉快。

@Html。DropDownListFor是非常棘手的选择项目,试试这个

@Html.DropDownListFor(m => m.SelectedSystem.SYSTEMNAME, 
new SelectList(Model.Systems, "SYSTEMNAME", "SYSTEMNAME", 
Model.SelectedSystem.SYSTEMNAME), "Select System", new { @class ="form-control"}

所以我更喜欢asp.net select

@{
var systemList = Model.Systems.Select(item=> new SelectListItem 
{ Text = item.SYSTEMNAME, 
Value = item.SYSTEMNAME
}).ToList();; 
}
......
<select class="form-control" asp-for="SelectedSystem.SYSTEMNAME" asp-items="@systemList"></select>

最新更新