通过一个操作在两个模型上执行创建操作

Pan*_*yay 2 upload scaffolding razor entity-framework-4.1 asp.net-mvc-3

我有两个模型:分类图片分别引用两个表,分类和图片.Category模型具有Picture模型的导航属性.

现在,我使用Scaffolding功能创建了一个控制器,其中包含类别的CRUD操作.以下是代码: -

public ActionResult Create()
{
    ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name");
    ViewBag.PictureId = new SelectList(db.Pictures, "Id", "PictureUrl");
    return View();
}
Run Code Online (Sandbox Code Playgroud)

自动生成的控制器操作使用SelectList列出数据库中的可用图片条目,并将其传递到下拉列表以供选择.这不是理想的情况,因为我想要的是无法用户上传图片,然后将引用添加到类别模型.之后,条目将保存到"类别和图片"表中.

Ole*_*yta 5

创建这样的模型:

public class FullCategoryModel
{
    public HttpPostedFileBase Picture { get; set; }
    public Category CategoryModel {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

在视图中:

@using (Html.BeginForm("Create", "Category", FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{  
  @Html.TextBoxFor(model => model.Category.Name)      // example, put there all category details 
  <input type="file" name="Picture" id="Picture" />      
  <input type="submit" value="Upload" />    
Run Code Online (Sandbox Code Playgroud)

}

然后创建动作:

[ActionName("Create")]
[HttpPost]
public ActionResult Create(FullCategoryModel model)
{
// here you can get image in bytes and save it in db, 
// also all category detail are avalliable here

MemoryStream ms = new MemoryStream();
model.Picture.InputStream.CopyTo(ms);
Image picture = System.Drawing.Image.FromStream(ms);

// save in db as separate objects, than redirect
return RedirectToAction("Index", "Category");
}
Run Code Online (Sandbox Code Playgroud)