我有查看,其中它在模型中循環並以可編輯模式顯示細節。其中一個模型值是從選擇列表類似下面如何設置默認值以在運行時在MVC中選擇列表
@if (Model != null)
{
for (int i = 0; i < Model.provider_service_dtls.Count; i++)
{
<tr>
<td> @Html.DropDownListFor(m => m.provider_service_dtls[i].activity_code_type,
(SelectList)@ViewBag.activity_code_type, "--- Select Activity Code Type ---", new { @class = "m-wrap" })</td>
<td>@Html.TextBoxFor(m => m.provider_service_dtls[i].activity_name)</td>
</tr>
}
}
這裏ViewBag.activity_code_type
包含在提交時Internal & Standard
的值,如果用戶選擇Internal
它的價值1
將傳遞給控制器,如果Standard
這將是2
這裏默認值將是"--- Select Activity Code Type ---"
現在,當我在編輯模式下打開相同的請求如果provider_service_dtls[i].activity_code_type
模型值是1
如果是2
,則選擇列表應該默認選擇爲Internal
和Standard
。
我編寫這樣
@Html.DropDownListFor(m => m.provider_service_dtls[i].activity_code_type,
(SelectList)@ViewBag.activity_code_type, Model.provider_service_dtls[i].activity_code_type)
但預期它給結果如下圖
這應該默認選中Internal
它無法正常工作。做到這一點的變化是什麼?
編輯
型號
public partial class provider_service_dtls
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long service_id { get; set; }
public long preapproval_id { get; set; }
public string activity_code_type { get; set; }
public string activity_type { get; set; }
public string activity_type_name { get; set; }
public string activity_code { get; set; }
public string activity_name { get; set; }
public string internal_activity_code { get; set; }
public string internal_activity_name { get; set; }
[ForeignKey("preapproval_id"), InverseProperty("provider_service_dtls")]
public virtual provider_preapproval preapproval { get; set; }
}
編輯模板
@model Provider.Models.provider_preapproval
@Html.DropDownListFor(m => m.activity_code_type, (SelectList)ViewData["options"])
查看
在for循環我編寫這樣
@Html.EditorFor(m => m.provider_service_dtls,
new { options = (SelectList)@ViewBag.activity_code_type })
我得到一個錯誤
'System.Web.Mvc.HtmlHelper' 並不 不包含 'EditorFor' 的定義和最好擴展方法 超負荷 'System.Web.Mvc.Html.EditorExtensions.EditorFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, 串,對象)' 具有一些無效參數
,所以我不能用這個forloop? – Sachu
那麼還有另一種選擇,但這意味着你需要在每次迭代中構建一個新的'SelectList'(效率不是很高)。如果你使用'ListBoxFor()',它也是唯一的方法,所以我建議你使用'EditorTemplate',這是一個更好的方法。更何況你現在有一個可重用的控件,所以在你的應用程序的其他任何地方你需要爲這個類型生成控件,你可以使用'@ Html.EditorFor()' –
也可以使用'@ Html.DropDownListFor()'在最後的代碼片段中是錯誤的。第三個參數用於生成一個'optionLabel'(即''---選擇活動代碼類型---「'你以前使用過的'),這就是爲什麼你的第二個圖像顯示'1''作爲第一個選項 –