2016-09-03 27 views
0

我正在創建一個空的子拉框,它根據其父項動態填充。當表單被引用時,屬性Platform始終爲空。爲什麼?將字符串屬性綁定到動態填充的下拉列表中並沒有設置值

這裏是我的ViewModel:

public class SkillsViewModel 
{ 
    public int SkillId { get; set; } 
    public string Platform { get; set; } 
} 

這是我的觀點:

@using (@Html.BeginForm("AddSkill", "AddSkills")) 
{ 
    @Html.DropDownListFor(m => m.SkillId, 
           new SelectList(ViewBag.SkillsFound, "Id", "SkillName"), "Select skill", 
           new { @class = "form-control", @onchange = "SkillSelected()" }) 

    @Html.DropDownListFor(m => m.Platform, 
          new SelectList(Enumerable.Empty<SelectListItem>()), 
          new { @class = "form-control" }) 

    <input type="submit" name="submit" value="Add skill" class="btn btn-success" /> 
} 

和控制器:

[HttpPost] 
public ActionResult AddSkill(SkillsViewModel model) 
{ 
    // model.Platform is always null 
    // to be implemented... 
    return RedirectToAction("Index"); 
} 

這裏是填充dropdown.It的紙條作品的權利 - 在下拉列表中添加字符串列表

​​

編輯:

這裏是返回字符串列表控制器。

public class GetSkillPlatformsController : Controller 
{ 
    [HttpPost] 
    public ActionResult Index(int skillId) 
    { 
     var Db = new DbContext(); 

     List<Platform> PlatformsFound = Db.Platforms.Where(pl => pl.PlatformSkill.Id == skillId).ToList(); 

     List<string> PlatformsNames = new List<string>(); 

     foreach(Platform pl in PlatformsFound) 
     { 
      PlatformsNames.Add(pl.PlatformName); 
     } 

     return Json(PlatformsNames); 
    } 
} 
+0

您需要顯示腳本,在其中填充第二個下拉列表 –

+0

那麼它的工作原理ks正確,並用字符串列表填充下拉列表,所以我認爲問題不應該在那裏。 –

+1

當然它:)。你添加選項的代碼是錯誤的 - 如果'data'是一個字符串,那麼它不能有'data.Id'屬性(因此每個選項都有一個'null'值)。你需要顯示控制器的方法,返回的數據生成的選項 –

回答

1

你的控制器方法返回的string集合,並在腳本中使用的

$.each(data, function (i, data) { 
    $("#Platform").append($('<option></option>').val(data.Id).html(data)); 
}); 

是設置每個選項的value屬性nullvalue=""),因爲datastringstring不包含名爲Id的屬性。

腳本改爲

$.each(data, function (i, data) { 
    $("#Platform").append($('<option></option>').text(data)); 
}); 

其中省略了value屬性,默認情況下將提交所選文本的價值(或者你可以使用.append($('<option></option>').val(data).text(data)

此外,可以簡化控制器代碼爲

[HttpPost] 
public ActionResult Index(int skillId) 
{ 
    var Db = new DbContext(); 
    var model = Db.Platforms.Where(pl => pl.PlatformSkill.Id == skillId).Select(pl => pl.PlatformName); 
    return Json(model); 
} 
相關問題