这就是我到目前为止所拥有的。它有效,但我知道这是不正确的,因为我在控制器中做数据库的东西,应该在模型中完成,但我不知道如何以这种方式完成它。
模型
public class files
{
public int fileid { get; set; }
public string fileName { get; set; }
public string filePath { get; set; }
}
控制器
public ActionResult Index()
{
IList<files> downloads = new List<files>();
// Get Users Role(s) thanks Ropstah
string[] userRoles = Roles.GetRolesForUser(User.Identity.Name);
string userRolesForSqlQuery = userRoles.Select(x => "'" + x + "'").Aggregate((a, b) => a + "," + b);
// MySql Connection thanks again Ropstah
string connectionString = "my data source";
var MySqlConnectionString = String.Format(@"SELECT fileid, fileName, filePath, FROM downloads
INNER JOIN downloadsroles on downloads.fileid = downloadsroles.downloadsid
WHERE downloadsroles.roleName IN ({0});", userRolesForSqlQuery);
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand comm = conn.CreateCommand();
MySqlDataReader Reader;
comm.CommandText = MySqlConnectionString;
conn.Open();
Reader = comm.ExecuteReader();
while (Reader.Read())
{
downloads.Add(new files() { fileName = Reader["fileName"].ToString(),
filePath = Reader["filePath"].ToString()});
}
conn.Close();
return View(downloads);
}
看法
@foreach (var downloads in ViewData.Model)
{
<tr>
<td>
@downloads.fileName
</td>
<td>
@downloads.filePath
</td>
</tr>
}