How do I get the last value from a list of models without looping it in MVC?
Here I need to get the last value from the list of models in the view without looping it. Here is my controller code
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;
}
and here I see the values looping the model and the total is 47, but I only need the 47th value, which is the last value without any loops.
View Code
@foreach (var item in Model)
{
@Html.EditorFor(modelItem => item.ThemeColor)
@Html.EditorFor(modelItem => item.LayoutDesign)
}
Any suggestion?
+3
source to share
2 answers
Use linq! In your case . Last () method .
Try:
@{ var last = Model.Last(); }
@Html.EditorFor(modelItem => last.ThemeColor)
@Html.EditorFor(modelItem => last.LayoutDesign)
+8
source to share