【发布时间】:2015-05-10 15:02:06
【问题描述】:
我创建多个模型
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=id 来自 DropDownListFor)并添加到数据库。如何使用 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" />
}
还有我的控制器,其中formCollection 中的Room.Id 始终=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()方法中,new { id = Model.Room.Id }正在添加一个 html 属性-不清楚您要对此做什么 (2) 您的 POST 方法签名应该是public ActionResult AddRoomImg(MultipleModel model, HttpPostedFileBase img)和 @ 987654334@ 将包含选定的值,img将包含文件。 (3) 你的<input type="file" ..>不是多个,那你为什么要使用foreach循环呢? (4) 使用仅包含您需要在视图中显示/编辑的那些属性的视图模型
标签: asp.net asp.net-mvc html.dropdownlistfor