【问题标题】:Returning view model cannot recognize entity framework返回视图模型无法识别实体框架
【发布时间】:2015-10-26 13:52:12
【问题描述】:

型号:

Public partial class tbl_pictures {

public int picture_id
public string picture_content
public int user_no (foreign key)

public virtual tbl_user tbl_user {get;set;}
}

视图模型:

public class MyViewModel 
public IEnumerable<Telephone_Search.Models.tbl_users> users;
public IEnumerable<Telephone_Search.Models.tbl_pictures> images;

家庭控制器:

 [HttpPost]
    public ActionResult Index(HttpPostedFileBase file, MyViewModel model , tbl_pics pic)
    {
        if (ModelState.IsValid)
        {
            if (file != null)
            {                 
                file.SaveAs(HttpContext.Server.MapPath("~/Images/")
                                                      + file.FileName);
                byte[] data = new byte[] { };
                using (var binaryReader = new BinaryReader(file.InputStream))
                {
                    data = binaryReader.ReadBytes(file.ContentLength);
                }
               pic.picture_content = file.FileName;
               pic.emp_no = 6;
               db.tbl_pictures.Add(pic);
               db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

         return this.View(new MyViewModel
        {
            images = pic //ERROR HERE
        });
    }

剃刀视图:

@foreach (var img in Model.images) {
        <img src="~/images/@img.profile_content" width="100" height="100"     />
        }
    @using (Html.BeginForm("Index", "Home", null, FormMethod.Post,
                      new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div class="editor-label">
            @Html.LabelFor(model => model.picture_content)
        </div>
        <div class="editor-field">
            <input id="ImagePath" title="Upload a product image"
                   type="file" name="file" />
        </div>
        <p><input type="submit" value="Create" /></p>
    }

当我返回一个视图时,img 状态它不能被隐式转换,因为存在显式覆盖? ,我的目标是在 tbl_pictures 中存储图像并返回一个视图模型,以便剃刀视图可以识别存储在 model.images 中的内容?

【问题讨论】:

  • tbl_picstbl_pictures一样吗?
  • 首先,至少给我们编译的代码。二、错误发生在哪里?
  • @Glitch100 是的,抱歉,代码状态为“此处出错”。

标签: c# model-view-controller entity-framework-4 viewmodel


【解决方案1】:

假设tbl_picstbl_pictures 相同,那么看起来您遇到的问题是您试图将单个对象传递给您的IEnumerable 在视图模型中。

而是创建一个新的ArrayList&lt;T&gt; 或任何实现 IEnumerable 接口并使用pic 填充它并将其分配给images 属性。

new MyViewModel
{
    images = new Telephone_Search.Models.tbl_pictures[] { pic };
}

感谢@Matias,使用数组代替列表

【讨论】:

  • 为了记录,也可以创建一个固定数组:images = new Telephone_Search.Models.tbl_pictures[] { pic }
  • 是的——任何东西都实现了接口,个人就像列表一样,但最好将数组作为单个元素来做。我会更新代码
  • 在剃刀视图 model.images 状态对象引用未设置为对象的实例...我不明白吗?我清楚地在我的视图中返回了图像。
  • 你做了我建议的改变吗@AqibMehrban
  • 是的,我做到了:) @Glitch100
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多