質問

2つのモデルがあります。 カテゴリー写真 これは、それぞれ2つのテーブル、カテゴリ、および写真を指します。カテゴリモデルには、画像モデルのナビゲーションプロパティがあります。

次に、カテゴリのCRUD操作を備えた足場機能を使用してコントローラーを作成しました。以下はコードです: -

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

自動化されたコントローラーアクションは、データベース内の利用可能な画像エントリをリストするためにSelectListを使用し、選択のためにドロップダウンリストに渡します。これは理想的なシナリオではありません。なぜなら、ユーザーが画像をアップロードできず、参照がカテゴリモデルに追加されることであるため、これは理想的なシナリオではありません。その後、エントリはカテゴリと写真のテーブルに保存されます。

役に立ちましたか?

解決 2

まず第一に、私は感謝したいと思います @nicklarsen 私の理解が良いと信じさせて、自分でタスクを達成できると信じています。

問題はそれほど難しくはありませんでしたが、私はASP.NET MVCに慣れていないので、物事は少し困惑していました。最初から、ViewModelのマージカテゴリと価格クラスが必要になるという概念があり、APIのアップロードが必要になるという概念がありました。しかし、どういうわけか、私は正しい場所にピースを取り付けることができませんでした。したがって、インターネットを介したさまざまな回帰と研究の後、私は次の方法でタスクを達成しました。

  • まず、ViewModelを作成しました

    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);
    }
    
  • そして最後に、DBの変更を保存するために以下のようにカテゴリの作成機能を書き直します

    [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();
    }
    

他のヒント

このようなモデルを作成します:

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");
}

MVCの足場機能は、2つのモデルの関係を「多くの人にとって」と見なしていると思います。そのため、2つのドロップダウンリストが作成されました。シナリオによると、「画像」モデルデータのない「カテゴリ」の作成ページを作成できます。これは、「画像」がここで主要なエンティティであるためです。したがって、写真でアクションを作成します。

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

        return View(picture);
    }

Create 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>
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top