Reputation: 71
I have view model which contains two tables however if I am updating my entity framework e.g.
View Model:
public class MyViewModel
{
public IEnumerable<Telephone_Search.Models.tbl_pics> images;
public IEnumerable<Telephone_Search.Models.tbl_users> users;
}
Controller :
[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);
}
and then use a view model within my razor view e.g. @model ViewModel and try to loop through the users by :
@foreach (var img in Model.images) {
<img src="~/images/@pic.picture" width="100" height="100" />
}
The values are returned as null?
Thank you
Upvotes: 0
Views: 198
Reputation: 4808
You viewmodel consists of two collections, images
and users
.
public class MyViewModel
{
public IEnumerable<Telephone_Search.Models.tbl_pics> images;
public IEnumerable<Telephone_Search.Models.tbl_users> users;
}
However, in your controller method you are only returning the collection images
. users
remains null.
[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.
}
You need to populate the users
collection in your controller method.
Secondly, this
@foreach (var img in Model.Users) {
<img src="~/images/@pic.picture" width="100" height="100" />
}
does not make sense. Where is @pic
defined here?
Upvotes: 2