[英]@Html.DropDownList return null to controller
我視圖中的DropDownList
顯示了相關選項供您選擇,但是無論我選擇什么,Controller中的folders
都將獲得null
。
為什么? 我該如何修復它,以便Controller中的folders
從視圖的DropDownList
獲取選定的選項?
PS-我沒有模特。
這是我的控制器:
//POST: Home
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> file, string folder, IEnumerable<SelectListItem> folders)
{
// some code here
}
這是我的看法:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken();
<div class="container">
<div class="form-horizontal">
<div class="form-group">
<p></p>
<label for="file">Upload Photo:</label>
<input type="file" name="file" id="file" accept="image/*" multiple="multiple"/>
</div>
<div class="form-group">
<div>
<label>Choose Album:</label>
@if (ViewBag.Folders != null)
{
@Html.DropDownList("folders", new SelectList(ViewBag.Folders as IEnumerable<SelectListItem>, "Value", "Text"), "--- Select Album ---", new { @class = "form-control" })
}
</div>
</div>
<div class="form-group">
<div>
<input type="submit" value="Upload" class="btn btn-default" />
</div>
</div>
</div>
</div>
}
謝謝。
為了得到該文件夾,給您的下拉列表相應的名稱...
@ Html.DropDownList(“文件夾” ...
將導致您的DDL具有名稱“文件夾” ...這將嘗試回發單個項目...方法中的folders
是IEnumerable<SelectListItem>
... modelbinder無法轉換該folders
...
嘗試
@ Html.DropDownList(“文件夾” ...
注意丟失的s
現在該名稱對應於您方法中的string folder
參數...活頁夾最有可能為您綁定...
如果您調試此類錯誤,請使用調試器查看HttpContext.Request.Params
,它將向您顯示發出請求時返回的內容...
參數類型應從IEnumerable更改為String,因為視圖僅返回選定的項目NOT集合。
//POST: Home
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> file, string folder, string folders)
{
// some code here
}
只是想給另一個選擇。 如果您能夠利用客戶端解決方案,則可以使用隱藏的輸入值和JQuery來增強這一功能。
添加隱藏的輸入控件:
<input name="selectedFolder" type="hidden" value="" />
添加一些jQuery:
<script type="text/javascript">
$(function(){
$("#folders").on("change", function {
$("#selectedFolder").val($(this).text());
});
});
</script>
謝謝Sakthivel Ganesan,將Controller中的IEnumerable<SelectListItem> folders
更改為string folders
,剩下要做的唯一一件事就是將我的Html.DropDownList
Value
更改為Text
這樣……
來自:
@Html.DropDownList("folders", new SelectList(ViewBag.Folders, "Value", "Text"), "--- Select Album ---", new { @class = "form-control" })
至:
@Html.DropDownList("folders", new SelectList(ViewBag.Folders, "Text", "Text"), "--- Select Album ---", new { @class = "form-control" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.