从DropDownList获取字符串

时间:2011-11-09 08:54:03

标签: c# asp.net-mvc asp.net-mvc-3 drop-down-menu

我有XML文件,其中包含我的数据,我想从dropdownlist中保存选择字符串到此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保存字符串(团队名称)。谢谢你的帮助

编辑: 我更新了控制器和视图方法的显示代码。

1 个答案:

答案 0 :(得分:1)

您将下拉列表绑定到Team复杂属性(DropDownList帮助程序的第一个参数)。这没有意义。您只能绑定标量值。我还建议你使用强类型的帮助程序:

@Html.DropDownListFor(x => x.Team.TeamID, (SelectList)ViewBag.Team, String.Empty)

这样,您将使用下拉列表中的选定值填充POST操作中的TeamID属性。

同时替换:

@Html.ValidationMessageFor(model => model.Team)

使用:

@Html.ValidationMessageFor(model => model.Team.TeamID)