gpt4 book ai didi

c# - 如何在不在 MVC 中循环的情况下从模型列表中获取最后一个值?

转载 作者:行者123 更新时间:2023-11-30 13:47:57 25 4
gpt4 key购买 nike

这里我需要在不循环的情况下从 View 中的模型列表中获取最后一个值..这是我的 Controller 代码

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;

}

在 View 中,我通过循环模型获取值,总计数为 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)

关于c# - 如何在不在 MVC 中循环的情况下从模型列表中获取最后一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com