2011-11-09 272 views
-1

我有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保存字符串(團隊名稱)。感謝您的幫助

編輯: 我更新了控制器和查看方法的顯示代碼。

+0

有什麼問題嗎?什麼不工作?您的下拉菜單無法正確顯示?或者你不知道如何從中獲取文本值?如果是這樣,您只需將名爲Team的字符串參數放到您的操作中。 – rouen

+0

DropDown渲染正確,但我真的不知道如何從中獲得價值。我試着用字符串參數,但它不工作。我得到錯誤:沒有類型爲'IEnumerable '的ViewData項具有'Team'鍵。 –

+0

你有表單和後期操作?它不清楚你想要做什麼,哪些不起作用。 – jrummell

回答

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) 
+0

當我嘗試此操作時,發佈時出現此錯誤:具有鍵「Team.TeamID」的ViewData項的類型爲「System.Int32」,但必須爲「 IEnumerable的」。 DDL是popolutated但不能發佈。 –