在这里,我需要从视图中的模型列表中获取最后一个值,而无需循环它。这是我的控制器代码
public IList<ProductDetailModel> GetWPDetails()
{
ProductDetailModel Viewmodel;
string funname = "GetCSpecialWPDetails";
List<ProductDetailModel> getWPDetails = new List<ProductDetailModel>();
getWPDetails = objrest.EcommerceWPDetails(funname);
List<ProductDetailModel> WPDetails = new List<ProductDetailModel>();
foreach (var item in getWPDetails)
{
Viewmodel = new ProductDetailModel();
Viewmodel.Productid = item.Productid;
Viewmodel.ProductName = item.ProductName;
Viewmodel.CategoryID = item.CategoryID;
Viewmodel.ProductRate = item.ProductRate;
Viewmodel.DiscountRate = item.DiscountRate;
Viewmodel.imageurl1 = item.imageurl1;
WPDetails.Add(Viewmodel);
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT ThemeColor,LayoutDesign FROM dbo.Cpecial_Partner_Design WHERE [PartnerID]='" + Partid + "'", con);
con.Open();
using (SqlDataReader myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
Viewmodel = new ProductDetailModel();
Viewmodel.ThemeColor = myReader["ThemeColor"].ToString();
Viewmodel.LayoutDesign = myReader["LayoutDesign"].ToString();
WPDetails.Add(Viewmodel);
}
myReader.Close();
}
con.Close();
return WPDetails;
}
在这里,我通过循环模型来获取值,总数为 47,但我需要的是我只需要第 47 个值,这是没有任何循环的最后一个值。
查看代码
@foreach (var item in Model)
{
@Html.EditorFor(modelItem => item.ThemeColor)
@Html.EditorFor(modelItem => item.LayoutDesign)
}
有什么建议吗?
使用 linq!在您的情况下.Last() 方法。
尝试:
@{ var last = Model.Last(); }
@Html.EditorFor(modelItem => last.ThemeColor)
@Html.EditorFor(modelItem => last.LayoutDesign)
你的模型似乎是一个IList<>,所以我建议简单地使用它:
var last;
if (Model != null && Model.Count > 0) last = Model[Model.Count - 1];
else
...