【问题标题】:Can't access data from ViewModel?无法从 ViewModel 访问数据?
【发布时间】:2015-10-23 15:13:50
【问题描述】:

我有一个包含两个表的视图模型,但是如果我正在更新我的实体框架,例如

查看模型:

public class MyViewModel
{
public IEnumerable<Telephone_Search.Models.tbl_pics> images;
public IEnumerable<Telephone_Search.Models.tbl_users> users;
}

控制器:

[HttpPost]
    public ActionResult Index(tbl_pics pic, HttpPostedFileBase file)
    {
        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 = file.FileName;
               pic.user_no = 20173;
               db.tbl_pics.Add(pic);
               db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        return View(pic);
    }

然后在我的剃刀视图中使用视图模型,例如@model ViewModel 并尝试通过以下方式遍历用户:

@foreach (var img in Model.images) {
<img src="~/images/@pic.picture" width="100" height="100" />
}

值返回为空?

谢谢

【问题讨论】:

  • 请发布您的控制器代码以查看视图的服务方式。
  • 控制器的更多代码会很有用
  • 看起来您的控制器代码正在返回 img 并且您的视图期望具有 Users 属性的视图模型。你确定你传递的是正确的值吗?
  • @ToddSprang 我不确定如何保存对实体框架的更改并将值传递给视图模型?
  • @Djeroen ,代码已更新!

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


【解决方案1】:

您的视图模型包含两个集合,imagesusers

public class MyViewModel
{
    public IEnumerable<Telephone_Search.Models.tbl_pics> images;
    public IEnumerable<Telephone_Search.Models.tbl_users> users;
}

但是,在您的控制器方法中,您只返回集合imagesusers 保持为空。

[HttpPost]
public ActionResult Index(tbl_pics pic, HttpPostedFileBase file)
{
    ....
    return View(pic); // you are only returning the images here, not the users, or the viewmodel.
}

您需要在控制器方法中填充users 集合。

其次,这个

@foreach (var img in Model.Users) {
    <img src="~/images/@pic.picture" width="100" height="100" />
}

没有意义。 @pic 这里定义在哪里?

【讨论】:

  • @pic 定义在 images/'pic' picture 中,pic 是别名为 users 的表格!
  • @AqibMehrban 那么您需要在问题中指定此信息。
  • @AqibMehrban 其实,再看你的评论,也没什么意义。
  • 道歉,我也已经从另一个动作控制器返回用户,该控制器成功工作,因为它确实从模型返回视图但是我不知道如何从这个动作返回图片视图。谢谢
  • 道歉,它的 var img 在 Model.images 而不是 Model.Users
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
相关资源
最近更新 更多