已上传文件列表展示问题求助:页面加载无列表+上传空引用异常
Let's walk through resolving both of your problems step by step. I've reviewed your code and found a few key gaps that are causing the behavior you're seeing.
1. Fixing the "Dataset List Not Showing on Page Load" Issue
Right now, your upload action isn't properly handling the initial GET request when the page loads. When a user first visits the page, there's no form data being sent, so the model parameter is null. Trying to assign model.datasetlist = model2 with a null model would cause an error (even if your SQL query works).
Here's how to fix this by splitting your action into GET and POST handlers:
Updated Controller Code (GET Handler)
[HttpGet] public ActionResult Upload() { // Initialize the view model first to avoid null references var model = new DatasetViewModel(); var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionstring)) { try { con.Open(); using (SqlCommand cmd = new SqlCommand("SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = @userid", con)) { cmd.Parameters.Add("@userid", SqlDbType.Text).Value = System.Web.HttpContext.Current.User.Identity.GetUserId(); using (SqlDataReader reader = cmd.ExecuteReader()) { // Initialize the list before adding items model.datasetlist = new List<DatasetDetail>(); while (reader.Read()) { var u = new DatasetDetail(); u.datasetid = reader["datasetid"].ToString(); u.dataset = reader["datasetname"].ToString(); // u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]); model.datasetlist.Add(u); } } } } catch (Exception ex) { ViewBag.Error = $"Failed to load your datasets: {ex.Message}"; } // The 'using' block automatically closes the connection - no need for finally! } return View(model); }
2. Fixing the NullReferenceException on Upload
The main issues here are:
- Your view model doesn't include a property for
datasetname, so the form value isn't being bound to the model. - You weren't reloading the dataset list after upload, and the model might be null if not properly initialized.
- You were missing the actual file/upload logic to save the dataset to your database.
Step 1: Update Your View Model
Add the datasetname property so the form can bind to it:
public class DatasetViewModel { public List<DatasetDetail> datasetlist { get; set; } public string datasetname { get; set; } // Add this to capture the dataset name from the form }
Step 2: Add the POST Handler for Uploads
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Upload(DatasetViewModel model, HttpPostedFileBase upload) { // First handle the file upload and database insertion if (upload != null && upload.ContentLength > 0) { try { var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionstring)) { con.Open(); // Insert the new dataset into your database using (SqlCommand cmd = new SqlCommand("INSERT INTO datasets (datasetname, userid, timestamp) VALUES (@datasetname, @userid, GETDATE())", con)) { cmd.Parameters.Add("@datasetname", SqlDbType.Text).Value = model.datasetname; cmd.Parameters.Add("@userid", SqlDbType.Text).Value = System.Web.HttpContext.Current.User.Identity.GetUserId(); cmd.ExecuteNonQuery(); } } ViewBag.Message = "File uploaded successfully!"; } catch (Exception ex) { ViewBag.Error = $"Upload failed: {ex.Message}"; } } else { ViewBag.Error = "Please select a file to upload."; } // Reload the dataset list to show the new entry var connectionstringList = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionstringList)) { try { con.Open(); using (SqlCommand cmd = new SqlCommand("SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = @userid", con)) { cmd.Parameters.Add("@userid", SqlDbType.Text).Value = System.Web.HttpContext.Current.User.Identity.GetUserId(); using (SqlDataReader reader = cmd.ExecuteReader()) { model.datasetlist = new List<DatasetDetail>(); while (reader.Read()) { var u = new DatasetDetail(); u.datasetid = reader["datasetid"].ToString(); u.dataset = reader["datasetname"].ToString(); // u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]); model.datasetlist.Add(u); } } } } catch (Exception ex) { ViewBag.Error = $"Failed to load datasets: {ex.Message}"; } } return View(model); }
Step 3: Fix the View's Dataset List Rendering
Your current loop is missing the @ to output the value, and should include a null check to avoid errors if the list is empty:
<div> @if (Model?.datasetlist != null && Model.datasetlist.Any()) { foreach (var u in Model.datasetlist) { <b>@u.dataset</b><br /> } } else { <p>No datasets uploaded yet.</p> } </div>
Key Notes
- Always initialize your view models and collections (like
datasetlist) to avoid null references. - Use
usingblocks for database connections/commands/readers - they automatically dispose resources, so you don't need to manually close connections. - Split GET/POST actions to separate initial page load logic from form submission logic.
内容的提问来源于stack exchange,提问作者Sartorialist

