从下拉列表中获取字符串
本文关键字:字符串 获取 下拉列表 | 更新日期: 2023-09-27 18:13:50
我有包含我的数据的XML文件,我想从下拉列表保存选择字符串到这个XML。在我看来,我有这个:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>MatchXML</legend>
...
<div class="editor-label">
@Html.LabelFor(model => model.Team)
</div>
<div class="editor-field">
@Html.DropDownList("Team", (SelectList)ViewBag.Team, String.Empty)
@Html.ValidationMessageFor(model => model.Team)
</div>
...
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
在控制器: public ActionResult Pridat()
{
ViewBag.Team = new SelectList(repo.GetTeams(), "Name", "Name");
return View();
}
[HttpPost]
public ActionResult Pridat(MatchXML match, string Team)
{
if (ModelState.IsValid)
{
try
{
ViewBag.Team = new SelectList(repo.GetTeams(), "Name", "Name");
match.Team = repo.GetTeamByName(Team);
repo.AddMatch(match);
return RedirectToAction("Index");
}
catch (Exception ex)
{
//error msg for failed insert in XML file
ModelState.AddModelError("", "Error creating record. " + ex.Message);
}
}
return View(match);
}
模型是:
public class MatchXML
{
public int MatchXMLID { get; set; }
public string Opponent { get; set; }
public DateTime MatchDate { get; set; }
public string Result { get; set; }
public Team Team { get; set; }
public int Round { get; set; }
}
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public virtual User Coach { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
我试图做一些修改来做到这一点,但它不工作。我可以做到这一点与TeamID和保存ID,但我想在xml保存字符串(球队的名字)。谢谢你的帮助
编辑:我更新了控制器和视图方法的show code
您正在将下拉列表绑定到Team
complex属性(DropDownList helper的第一个参数)。这说不通啊。只能绑定到标量值。我还建议您使用强类型版本的帮助器:
@Html.DropDownListFor(x => x.Team.TeamID, (SelectList)ViewBag.Team, String.Empty)
这样,您将使用从下拉菜单中选择的值填充POST操作中的TeamID
属性。
也替换:
@Html.ValidationMessageFor(model => model.Team)
:
@Html.ValidationMessageFor(model => model.Team.TeamID)