我有XML文件,其中包含我的数据,我希望从下拉列表保存选择字符串到这个XML。 在我看来,我有这样的:从DropDownList获取字符串
@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保存字符串(团队名称)。感谢您的帮助
编辑: 我更新了控制器和查看方法的显示代码。
有什么问题吗?什么不工作?您的下拉菜单无法正确显示?或者你不知道如何从中获取文本值?如果是这样,您只需将名为Team的字符串参数放到您的操作中。 – rouen
DropDown渲染正确,但我真的不知道如何从中获得价值。我试着用字符串参数,但它不工作。我得到错误:没有类型为'IEnumerable'的ViewData项具有'Team'键。 –
你有表单和后期操作?它不清楚你想要做什么,哪些不起作用。 – jrummell