包含模型列表的模型(MVC-3,Razor) [英] Model Containing List of Models (MVC-3, Razor)

查看:21
本文介绍了包含模型列表的模型(MVC-3,Razor)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经困扰我两天了.有一些类似的帖子,但没有一个能完全解决我的问题.

使用 MVC-3,Razor 语法:

-- EDIT.cshtml --

@using (Html.BeginForm("Edit", "My", FormMethod.Post, new { enctype = "multipart/form-data" })){<!-- 一些字段...--><div class="editor-field">@Html.TextAreaFor(m => m.LongDescription)@Html.ValidationMessageFor(m => m.LongDescription)

<!-- 一些其他领域的工作...包括图片上传(摘要).--><input name="button" type="submit" value="添加图片"/><!-- 图片项目显示-->@foreach(Model.ThumbnailImagePathAndNames 中的 var 缩略图){<img src="@Url.Content(@thumbnail.ThumbnailPicturePath)" alt="" width="200"/>@Html.RadioButtonFor(o=>o.SelectedImage, @thumbnail.ImageGUID) 主图片<!-- 标记为删除的复选框-->@Html.CheckBoxFor(o=>thumbnail.Delete) 删除 ????????<!---- 这是一个问题-我不明白这应该如何工作-->}<input id="Submit1" name="button" type="submit" value="完成编辑!"/>}

-- MyController.cs --

 [HttpPost]公共 ActionResult 编辑(字符串按钮,HttpPostedFileBase 文件,MyMainModel 模型){//如果按钮 = 提交图片,在此处处理图片并中断(长篇故事)//保存模型数据//如果有效,保存并重定向//无效或错误,像正常一样加载视图但带有错误消息模型加载缩略图();返回视图(模型);}

-- MyMainModel.cs --

公共类 MyMainModel{//一些属性...公共指南?SelectedImage { 获取;放;}[显示(名称=详细说明")]公共字符串 LongDescription { 获取;放;}//还有一些属性....//最后是我的模型列表公共 IListThumbnailImagePathAndNames { 获取;放;}public void LoadThumbnails(){//加载初始缩略图模型this.ThumbnailImagePathAndNames = new List(readDataService.GetThumbnailModels(this.SomeID));}}

-- ThumbnailModels.cs --

公共类 ThumbnailModel{公共 GUID ImageGUID { 获取;放;}公共字符串 FullSizePicturePath { 获取;放;}public String ThumbnailPicturePath { get;放;}公共布尔删除{得到;放;}}

有什么问题吗?好了,当完成编辑!"按钮被按下,MyController 的 Edit 被调用,正如预期的那样,所有 MyMainModle 的数据都完好无损......除了 ThumbnailModel 的列表 - 那些结果是空的.

这应该怎么做?我已经尝试了很多不同的方法来解决这个问题,包括制作一个可编辑的模板和使用 EditFor(o=>...集合中的单个项目 - 我尝试了两种方法.所有过去都可以工作,直到我添加了删除复选框的复杂性,因此需要检索 ThumbnailModels 列表以检查内部 Delete 属性值.

感谢大家阅读并试图理解这一点.

[免责声明 - 一些变量和方法名称已更改以保护无辜的程序.很多代码都被剥离了,换成了注释代码.]

解决方案

这是我用来说明一些概念的示例:

型号:

公共类 MyMainModel{公共指南?SelectedImage { 获取;放;}公共字符串 LongDescription { 获取;放;}公共 IEnumerableThumbnailImagePathAndNames { 获取;放;}公共 HttpPostedFileBase 文件 { 获取;放;}}公共类缩略图模型{公共 GUID ImageGUID { 获取;放;}公共布尔删除{得到;放;}}

控制器:

公共类 HomeController : 控制器{公共 ActionResult 索引(){var 模型 = 新的 MyMainModel{//TODO: 从存储库中获取而不是硬编码ThumbnailImagePathAndNames = new[]{新缩略图模型 { ImageGUID = Guid.NewGuid() },新缩略图模型 { ImageGUID = Guid.NewGuid() },新缩略图模型 { ImageGUID = Guid.NewGuid() },}};返回视图(模型);}[HttpPost]公共 ActionResult 索引(MyMainModel 模型){...模型将被正确绑定在这里}}

查看:

@model AppName.Models.MyMainModel@{ViewBag.Title = "索引";布局 = "~/Views/Shared/_Layout.cshtml";}@using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" })){<div class="editor-field">@Html.TextAreaFor(m => m.LongDescription)@Html.ValidationMessageFor(m => m.LongDescription)

<input type="file" name="file"/><!-- 上传和完成提交使用不同的名称按钮,以便您可以区分单击了哪个在 POST 操作中--><input name="upload" type="submit" value="添加图片"/>@Html.EditorFor(x => x.ThumbnailImagePathAndNames)<input name="complete" type="submit" value="完成编辑!"/>}

编辑器模板:(~/Views/Home/EditorTemplates/ThumbnailModel.cshtml):

@model AppName.Models.ThumbnailModel<!-- 将图像 id 作为隐藏字段传递 -->@Html.HiddenFor(x => x.ImageGUID)@Html.CheckBoxFor(x => x.Delete)

This problem has been plaguing me for two days now. There are some similar posts, but none that address my problem completely.

Using MVC-3, Razor syntax:

-- EDIT.cshtml --

@using (Html.BeginForm("Edit", "My", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <!-- Some fields... -->
    <div class="editor-field">
        @Html.TextAreaFor(m => m.LongDescription)
        @Html.ValidationMessageFor(m => m.LongDescription)
    </div>

    <!-- Some more fields work... Including picture upload (summary).-->
    <input name="button" type="submit" value="Add Picture" />

    <!-- Picture Item display -->
    @foreach(var thumbnail in Model.ThumbnailImagePathAndNames) 
    {
      <img src="@Url.Content(@thumbnail.ThumbnailPicturePath)" alt="" width="200" />
      @Html.RadioButtonFor(o=>o.SelectedImage, @thumbnail.ImageGUID)  Primary Picture 
      <!-- Checkbox to mark for deletion -->
      @Html.CheckBoxFor(o=>thumbnail.Delete) Delete ???????? <!---- Here is a problem - I don't understand how this should work -->
    }
    <input id="Submit1" name="button" type="submit" value="Complete Edit!" />
}

-- MyController.cs --

 [HttpPost]
 public ActionResult Edit(String button, HttpPostedFileBase file, MyMainModel model)
 {
     // if button = submit picture,  work with picture here and break(long story)

     // save model data
         // if valid, save and redirect


     // not valid or error, load up view like normal but with error messages
     model.LoadThumbnails();
     return View(model);

 }

-- MyMainModel.cs --

public class MyMainModel
{
    // some properties...
     public Guid? SelectedImage { get; set; }

    [Display(Name = "Detailed Description")]
    public String LongDescription { get; set; }

    // some more properties....


    // and finally my list of models
    public IList<ThumbnailModel> ThumbnailImagePathAndNames { get; set; }

    public void LoadThumbnails()
    {
         // load up initial thumbnail models
         this.ThumbnailImagePathAndNames = new List<ThumbnailModel>(readDataService.GetThumbnailModels(this.SomeID));
    }
}

-- ThumbnailModels.cs --

public class ThumbnailModel
{
    public Guid ImageGUID { get; set; }
    public String FullSizePicturePath { get; set; }
    public String ThumbnailPicturePath { get; set; }

    public bool Delete { get; set; }
}

So whats the problem? Well, when the "Complete Edit!" button is pressed, the MyController's Edit is called, as expected with all the MyMainModle's data in tact.... except for the list of ThumbnailModel's - those turn out to be null.

How is this supposed to be done? I have tried many different approaches to this including making an editable template and using EditFor(o=>... all to no avail (this became confusing as I didn't know if the EditFor was supposed to be for the entire collection or just a single item in the collection - I tried both ways). All used to work until I added the complexity of the checkbox for deletion, therefore needing to retrieve the list of ThumbnailModels to check that internal Delete property value.

Thank you all for reading and trying to understand this.

[Disclaimer - some variable and method names have been changed to protect the innocent program. A lot of code has been stripped away and replaced by comment code.]

解决方案

Here's an example that I've put to illustrate some concepts:

Model:

public class MyMainModel
{
    public Guid? SelectedImage { get; set; }
    public string LongDescription { get; set; }

    public IEnumerable<ThumbnailModel> ThumbnailImagePathAndNames { get; set; }

    public HttpPostedFileBase File { get; set; }
}

public class ThumbnailModel
{
    public Guid ImageGUID { get; set; }
    public bool Delete { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyMainModel
        {
            // TODO: fetch from the repository instead of hardcoding
            ThumbnailImagePathAndNames = new[] 
            {
                new ThumbnailModel { ImageGUID = Guid.NewGuid() },
                new ThumbnailModel { ImageGUID = Guid.NewGuid() },
                new ThumbnailModel { ImageGUID = Guid.NewGuid() },
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyMainModel model) 
    {
        ... the model will be properly bound here
    }
}

View:

@model AppName.Models.MyMainModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="editor-field">
        @Html.TextAreaFor(m => m.LongDescription)
        @Html.ValidationMessageFor(m => m.LongDescription)
    </div>
    <input type="file" name="file" />
    <!-- Use different names for the upload and complete submit
         buttons so that you can distinguish which one was clicked
         in the POST action 
    -->
    <input name="upload" type="submit" value="Add Picture" />

    @Html.EditorFor(x => x.ThumbnailImagePathAndNames)    
    <input name="complete" type="submit" value="Complete Edit!" />
}

Editor template: (~/Views/Home/EditorTemplates/ThumbnailModel.cshtml):

@model AppName.Models.ThumbnailModel
<!-- Pass the image id as hidden field -->
@Html.HiddenFor(x => x.ImageGUID)
@Html.CheckBoxFor(x => x.Delete)

这篇关于包含模型列表的模型(MVC-3,Razor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆