MVC 的新手,我正在尝试获得一个有效的模型视图组件。唯一的限制是数据由 C# 类中的存储过程填充,并且 PartialView 使用 Razor 并存储在 _Shared 文件夹中,因此所有页面都可以引用它。
我认为可能有用的只有 ViewModel,BreadcrumbViewModel.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace Web.Controllers.ViewModels
{
public class BreadcrumbViewModel
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Label { get; set; }
public string URL { get; set; }
public int SortOrder { get; set; }
public int InverseDepth { get; set; }
}
public class BreadcrumbsViewModel
{
public List<BreadcrumbViewModel> getBreadcrumbModel(string thisURL)
{
//thisURL contains the path of the current page, so the stored proc can find its parents.
List<BreadcrumbViewModel> listBVM = new List<BreadcrumbViewModel>();
BreadcrumbViewModel model;
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDataContext"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "getBreadcrumb";
cmd.Parameters.Add(new SqlParameter("@thisURL", SqlDbType.NVarChar));
cmd.Parameters["@thisURL"].Value = thisURL;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
model = new BreadcrumbViewModel
{
Id = Convert.ToInt32(reader[0]),
ParentId = Convert.ToInt32(reader[1]),
Label = reader[2].ToString(),
URL = reader[3].ToString(),
SortOrder = Convert.ToInt32(reader[4]),
InverseDepth = Convert.ToInt32(reader[5])
};
listBVM.Add(model);
}
}
}
}
if (listBVM == null)
{
model = new BreadcrumbViewModel
{
Id = 1,
ParentId = 0,
Label = "Home",
URL = "/",
SortOrder = 1,
InverseDepth = 1
};
listBVM.Add(model);
}
return listBVM;
}
}
}
如果这个 ViewModel 是正确的,那么引用 List<> 的 Controller 和 PartialView 会是什么样子?