2

我有两个模型:类别图片它分别引用两个表,类别和图片。类别模型对图片模型具有导航属性。通过一个动作在两个模型上执行创建操作

现在,我创建了一个控制器,使用脚手架功能和类别的CRUD操作。以下是代码: -

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

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

+3

你不必坚持脚手架。如果它不适合您的需求,那么它只是为您提供了一个良好的开端,用代码替代它。这听起来像你对你想要做的事情有很好的理解,所以不要被卡住,认为你必须遵循脚手架,只要将它删除并写出你所需要的代码即可。 –

+1

@NickLarsen,谢谢你的伴侣让我放心。我已经完成了任务并发布了答案:-) –

回答

2

首先,我要感谢@NickLarsen让我相信,我的理解是好的,我可以实现自己的任务。

问题不是太强悍,但因为我是Asp.net MVC的新手,事情有点令人费解。从一开始,我就有了一个概念,那就是我需要一个ViewModel合并Category和Price类,然后再上传一个图片上传API。但是,不知何故,我无法将这些作品放在正确的位置。各种回归和研究在互联网上后,因此,我在下面的方式实现的任务: -

  • 首先,我创建了一个视图模型

    public class CatPicView 
    { 
        public Category Category { get; set; } 
        public Picture Picture { get; set; } 
    } 
    
  • 其次,我加了Uploadify javascript API

    <script type="text/javascript"> 
        $('#file_upload').uploadify({ 
         'uploader': '@Url.Content("~/uploadify/uploadify.swf")', 
         'script': '@Url.Action("Upload", "Category")', 
         'cancelImg': '@Url.Content("~/uploadify/cancel.png")', 
         'buttonText': 'Upload', 
         'folder': '@Url.Content("~/content/images")', 
         'fileDesc': 'Image Files', 
         'fileExt': '*.jpg;*.jpeg;*.gif;*.png', 
         'auto': true, 
         'onComplete': function (event, ID, fileObj, response, data) { 
           var json = jQuery.parseJSON(response); 
           $("#pictureImage").html("<img src='"+json+"' alt='"+json+"' height='100px' width='100px'/>"); 
           $("#Picture_PictureUrl").val(json); 
           $("#pictureRemove").show(); 
          } 
         }); 
    </script> 
    
  • 迷上API到以下服务器功能进行重命名并保存到文件夹

    [HttpPost] 
    public ActionResult Upload(HttpPostedFileBase fileData) 
    { 
        if (fileData != null && fileData.ContentLength > 0) 
        { 
         //var fileName = Server.MapPath("~/Content/Images/" + Path.GetFileName(fileData.FileName)); 
         int pictureCount = 800000; 
         pictureCount += db.Pictures.Count(); 
         string extension = Path.GetExtension(fileData.FileName); 
         string renamedImage = Server.MapPath("~/Content/Images/Categories/cat" + pictureCount + extension); 
         fileData.SaveAs(renamedImage); 
         return Json("/Content/Images/Categories/" + Path.GetFileName(renamedImage)); 
        } 
        return Json(false); 
    } 
    
  • ,最后,改写了分类创建如下功能的更改保存到数据库

    [HttpPost] 
    public ActionResult Create(CatPicView catPic) 
    { 
        if (ModelState.IsValid) 
        { 
         if (!String.IsNullOrEmpty(catPic.Picture.PictureUrl)) 
         { 
          Picture picture = new Picture(); 
          picture.PictureUrl = catPic.Picture.PictureUrl; 
          db.Pictures.Add(picture); 
          catPic.Category.PictureId = picture.Id; 
         } 
         db.Categories.Add(catPic.Category); 
         db.SaveChanges(); 
         return RedirectToAction("Index"); 
        } 
        return View(); 
    } 
    
0

我想MVC脚手架功能看到两个模型的关系为“多对多”。这就是为什么它为你创建了两个下拉列表。根据你的情况,你可以做“类别”创建页面没有“图片”模型数据,因为“图片”是这里的主要实体。所以在图片中创建动作。

[HttpPost] 
    public ActionResult Create(Picture picture) 
    { 
     if (ModelState.IsValid) 
     { 
      databaseContext.Pictures.Add(picture); 
      databaseContext.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(picture); 
    } 

在创建图片

@model YourProjectName.Models.Picture 
<h2>Create</h2> 
@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>Picture</legend> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.Url) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Url) 
     @Html.ValidationMessageFor(model => model.Url) 
    </div> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.Categories.CategoryID, "Category") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("CategoryID", "Choose Category") 
     @Html.ValidationMessageFor(model => model.Categories.CategoryID) 
    </div> 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
} 
+0

*** MVC脚手架功能将两个模型的关系看作“多对多”***,我不确定为什么你这样想,但事情不是这样这种方式 –

5

这样创建模型视图页面:

public class FullCategoryModel 
{ 
    public HttpPostedFileBase Picture { get; set; } 
    public Category CategoryModel {get; set;} 
} 

鉴于:

@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" />  

}

然后创建行动:

所有的
[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"); 
} 
+0

你的ViewModel的基本思想是绝对正确的....休息我需要运行,看看它是如何执行:-) ....我也在以另一种方式工作....将选择此为接受如果它解析我的methodolgy .....感谢队友的时间和答案.... + 1 –

+0

我很高兴我的答案帮助你 –

+0

我已经发布我的答案。你可能想检查一下。 –

相关问题