我創建多個模型獲取DropDownListFor選定值
public class MultipleModel
{
public Photo Photo { get; set; }
public Room Room { get; set; }
}
:
public class Room
{
public int Id { get; set; }
public string NumberRoom { get; set; }
public virtual ICollection<Photo> Photo { get; set; }
}
public class Photo
{
public int Id { get; set; }
public string PhotoName { get; set; }
public int Roomid { get; set; }
public virtual Room Room { get; set; }
}
在點擊Submit
在我看來,我要上傳圖片與從名稱的文件夾DropDownListFor所選項目(例如/ images/2 /,其中2 =來自DropDownListFor
的ID)並添加到數據庫。我如何使用Html.BeginForm從DropDownListFor正確發送選定的項目? 我的觀點:
@using Hotel.BusinessObject
@model MultipleModel
@using (Html.BeginForm("AddRoomImg", "Admin",
FormMethod.Post, new { enctype = "multipart/form-data", id = Model.Room.Id}))
{
<div>@Html.DropDownListFor(m=> m.Room.Id, ViewBag.roomlist as SelectList, "Select Room")</div>
<input type="file" name="img" />
<input type="submit" value="upload" />
}
而且我的控制器,其中Room.Id
在formCollection
始終= 0和int? id
不工作,並返回NULL
public ActionResult AddRoomImg()
{
ViewBag.roomlist = new SelectList(db.Room, "Id", "NumberRoom");
return View();
}
[HttpPost]
public ActionResult AddRoomImg(FormCollection formCollection, int? id)
{
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
if (file.ContentLength > 0)
{
ImageUpload imageUpload = new ImageUpload { Width = 600 };
ImageResult imageResult = imageUpload.RenameUploadFile(file);
if (imageResult.Success)
{
//TODO: write the filename to the db
}
else
{
ViewBag.Error = imageResult.ErrorMessage;
}
}
}
(1)在'BeginForm()'方法,'新{ID = Model.Room.Id}'被添加HTML屬性 - 它不清楚是什麼你想用這個(2)你的崗位上做方法簽名應該是'public ActionResult AddRoomImg(MultipleModel model,HttpPostedFileBase img)'和'model.Room.Id'將包含選定的值,'img'將包含該文件。 (3)你的''不是多個,所以你爲什麼使用'foreach'循環? (4)使用僅包含視圖中需要顯示/編輯的屬性的視圖模型 –