如果视图中的条件在一个视图中有两个模型,我的方法和位置有问题。
这是视图
public int PIC_ID { get; set; }
public string pic_name { get; set; }
public Nullable<int> belong_id { get; set; }
public byte[] pic { get; set; }
这是图片模型
public int SPID { get; set; }
public string Sp_email { get; set; }
public string Sp_password { get; set; }
public string Sp_name { get; set; }
这是service_provider模型
public ActionResult Index(){
ViewBag.service_provider = dc.service_provider;
ViewBag.pictures = dc.pictures;
return View();
}
这是我的控制器
{{1}}
上述视图的目的是显示service_provider的详细信息,其中图片中的 belongs_id 等于service_provider中的 SPID 。但我无法理解如果条件我在哪里添加。我正在使用数据库第一种方法
答案 0 :(得分:4)
如果使用强类型模型而不是ViewBag
,则会容易得多。然后,您可以向模型或控制器添加逻辑。我个人更容易阅读和测试。它还可以防止语法错误。
Models.cs
public class Picture {
public int PIC_ID { get; set; }
public string pic_name { get; set; }
public Nullable<int> belong_id { get; set; }
public byte[] pic { get; set; }
// added - your FK pointing back to the corresponding service_provider
public int SPID { get; set; }
// added - the corresponding service_provider
public service_provider ServiceProvider { get; set; }
}
public class service_provider {
public int SPID { get; set; }
public string Sp_email { get; set; }
public string Sp_password { get; set; }
public string Sp_name { get; set; }
// added
public ICollection<Picture> Pictures {get;set;}
}
Controller.cs
public ActionResult Index(){
var service_provider = dc.service_provider.Inculde(x => x.Pictures);
// var pictures = dc.pictures;
// code to add the pictures to the correct service_provider instance
// ideally this should already be reflected in your model.
// If you are using EF you should be modeling this using proper data relations
// that would allow you to execute an .Include statement on the retrieval
// and pass the model directly into the View without the need for an additional call to pictures as the service_provider would then already contain the relations
return View(service_provider);
}
View.cshtml
@model IEnumerable<service_provider>
@*This following line indicates that it is a list of service_provider hense the IEnumerable*@
@foreach (service_provider SP in Model){
<tr>
<td>@SP.Sp_email</td>
<td>@SP.Sp_name</td>
<td>@SP.city.Cityname</td>
</tr>
@*Iterate over the pictures on each model.
You can still split this if you want all service providers and then all pictures.*@
@foreach (picture img in SP.Pictures){ @*changed to still look at the model*@
<tr><td><img src="data:image/png;base64,@Convert.ToBase64String(img.pic,0,img.pic.Length)" width="100" /></td></tr>
}
}
答案 1 :(得分:0)
尝试:
@foreach (picture img in ViewBag.pictures)
{
if(img.PIC_ID == ViewBag.service_provider.SPID)
{
<tr><td><img src="data:image/png;base64,@Convert.ToBase64String(img.pic,0,img.pic.Length)" width="100" /></td></tr>
}
}
BTW - 也许更好的方法 - 检查服务器端并返回你需要的图片吗?