我有一个表单,用户可以上传文件,然后查看他们上传的列表。我遇到了两个问题:
用于获取数据集列表的控制器如下所示。当然,用于上载数据集的控制器是不同的,但它接受HttpPostedFileBase和datasetName。它只返回ViewBag.error / ViewBag.message。
public ActionResult upload(DatasetViewModel model)
{
List<DatasetDetail> model2 = new List<DatasetDetail>();
var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionstring))
try
{
// Your code
con.Open();
using (SqlCommand cmd = new SqlCommand("", con))
{
cmd.CommandText = "SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = @userid";
cmd.Parameters.Add("@userid", SqlDbType.Text);
cmd.Parameters["@userid"].Value = System.Web.HttpContext.Current.User.Identity.GetUserId();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var u = new DatasetDetail();
u.datasetid = reader["datasetid"].ToString();
u.dataset = reader["datasetname"].ToString();
/* u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]);*/
model2.Add(u);
}
}
}
catch
{
// Catch exception
}
finally
{
// Close the connection
con.Close();
}
model.datasetlist = model2;
return View(model);
}
查看:
@model WebApplication12.Models.DatasetViewModel
<div style="width: 320px;">
<h2>Manage Datasets</h2>
<a href="~/Content/ExcelTemplate.xlsx">Download Excel Template</a>
@using (Html.BeginForm("upload", "Dashboard", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group">
<label>Dataset Name:</label>
<br />
<input type="text" id="datasetname" name="datasetname" />
</div>
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-block" />
</div>
}
</div>
<div id="response"></div>
@if (ViewBag.Message != null)
{
<div class="alert alert-success" role="alert">@Html.Raw(ViewBag.Message)</div>
}
@if (ViewBag.Error != null)
{
<div class="alert alert-error" role="alert">@Html.Raw(ViewBag.Error)</div>
}
<div>
@foreach (var u in Model.datasetlist)
{
<b>u.dataset</b>
}
</div>
相关模型:
public class DatasetViewModel
{
public List<DatasetDetail> datasetlist { get; set; }
}
public class DatasetDetail
{
public string datasetid { get; set; }
public string dataset { get; set; }
/* public DateTime timestamp { get; set; }*/
}