I am working on an ASP.NET MVC application. I want to insert multiple rows at once into a database table. I am using a database-first approach.
I am facing an error
Object reference not set to an instance of an object
Can you guide me how to resolve it?
Here is code of myapp model class:
namespace MyApp.Models
{
using System;
using System.Collections.Generic;
public partial class tbl_hgt
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public decimal Height { get; set; }
public decimal Weight { get; set; }
}
}
This is the myapp view. I guess I have problem in view but not sure
@model IEnumerable<MyApp.Models.tbl_hgt>
@{
ViewBag.Title = "InsertRows";
}
<h2>InsertRows</h2>
@using (Html.BeginForm("InsertRows", "Home", FormMethod.Post))
{
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Height</th>
<th>Weight</th>
</tr>
@for (int i = 0; i < 5; i++)
{
<tr>
<td>@Html.TextBox("Id[" + i + "]")</td>
<td>@Html.TextBox("Name[" + i + "]")</td>
<td>@Html.TextBox("Age[" + i + "]")</td>
<td>@Html.TextBox("Gender[" + i + "]")</td>
<td>@Html.TextBox("Height[" + i + "]")</td>
<td>@Html.TextBox("Weight[" + i + "]")</td>
</tr>
}
</table>
<input type="submit" value="Submit" />
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Here is the code of myapp
controller class. I am not sure should I create one more action method to view.
using MyApp.Models;
using System.Web.Mvc;
public class myController : Controller
{
public ActionResult InsertRows(int[] Id, string[] Name, int[] Age, string[] Gender, decimal[] Height, decimal[] Weight)
{
// Create a context object to access the database
using (var db = new Employee_DbEntities())
{
// Loop through the arrays and create a new row object for each row
for (int i = 0; i < 5; i++)
{
var row = new tbl_hgt();
row.Id = Id[i];
row.Name = Name[i];
row.Age = Age[i];
row.Gender = Gender[i];
row.Height = Height[i];
row.Weight = Weight[i];
// Add the row object to the context
db.tbl_hgt.Add(row);
}
// Save the changes to the database
db.SaveChanges();
}
// Return a view or a message to confirm the insertion
return View();
}
}
This is the error I get:
I am just learning ASP.NET MVC - please help me to understand this error.