返回视图模型无法识别实体框架

时间:2015-10-26 13:52:12

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

型号:

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

Razor查看:

@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中存储图像并返回一个视图模型,这样剃刀视图就可以识别存储的模型.images?

1 个答案:

答案 0 :(得分:1)

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

而是创建一个新的ArrayList<T>或任何实现IEnumerable接口的东西,并用pic填充它并将其分配给images属性。

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

由于@ Matias

,使用的数组代替了List