Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
After clicking on the create button in the crud operation of asp.net mvc the actual issue is occuring in the controller where it returns null reference exception in the create method of the student1controller.cs file . Please Find or help with a solution.

What I have tried:

View(Create.html)
@model WebApplication3.student1

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm("Create", "student1", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Registration Form for Students</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @*<div class="form-group">
                @Html.LabelFor(model => model.student_id, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.student_id, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.student_id, "", new { @class = "text-danger" })
                </div>
            </div>*@

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Last_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Last_name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Last_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.phone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
            @Html.LabelFor(model => model.gender, "Male:")
            @Html.RadioButtonFor(model => model.gender, "Male")
            @Html.LabelFor(model => model.gender, "Female:")
            @Html.RadioButtonFor(model => model.gender, "Female")
            @Html.LabelFor(model => model.gender, "Others:")
            @Html.RadioButtonFor(model => model.gender, "Others")
            @Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })
        </div>

            
                   
               
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.dob, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.dob, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.dob, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.hobbies, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
              
                @foreach (var item in ViewBag.hobby)
                {
                    <input type="checkbox" name="hobb" value="@item.Value" />@item.Text
                }
                @*@Html.EditorFor(model => model.hobbies, new { htmlAttributes = new { @class = "form-control" } })*@

                @*@Html.CheckBoxFor(model => model.hobbies,true)*@
                @*@Html.LabelFor(model => model.hobbies, "Singing")
                @Html.CheckBoxFor(model => model.hobbies, "Singing")
                @Html.LabelFor(model => model.hobbies, "Reading")
                @Html.CheckBoxFor(model => model.hobbies, "Reading")
                @Html.LabelFor(model => model.hobbies, "Dancing")
                @Html.CheckBoxFor(model => model.hobbies, "Dancing")*@



            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


(student1controller.cs)
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication3;

namespace WebApplication3.Controllers
{
    public class student1Controller : Controller
    {
        private preet_testEntities db = new preet_testEntities();

        // GET: student1
        public ActionResult Index()
        {
           

            return View(db.student1.ToList());


        }
        //[HttpPost]
        //public string Index1(IEnumerable<student1> students)
        //{
        //    if (students.Count(x => x.hobbies) == 0)
        //    {
        //        return "please select a value";
        //    }
        //}
        // GET: student1/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            return View(student1);
        }

        // GET: student1/Create
        public ActionResult Create()
        {
            var list = new SelectList(new[]
                                             {
                                              new {ID="Reading",Name="Reading"},
                                              new{ID="Writing",Name="Writing"}
                                          },
                               "ID", "Name", 1);
            ViewBag.hobby = list;
            return View();
        }

        // POST: student1/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        
        public ActionResult Create(student1 student1,FormCollection fc)
        {
            if (ModelState.IsValid)
            {
                
                student1 obj = db.student1.Find(student1.student_id);

                obj.hobbies = fc["hobb"] != null ? fc["hobb"].ToString() : obj.hobbies; //the above line is where the error occurs.
                db.SaveChanges();
                  ViewBag.hobby=obj.hobbies;
                return RedirectToAction("Index");
            }

            return View(student1);
        }

        // GET: student1/Edit/5
        public ActionResult Edit(int? id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            var list = new SelectList(new[]
                                             {
                                              new {ID="Reading",Name="Reading"},
                                              new{ID="Writing",Name="Writing"}
                                          },
                               "ID", "Name", 1);
            ViewBag.hobby = list;
            
            return View(student1);
        }

        // POST: student1/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit( student1 student1 ,FormCollection fc)
        {
            if (ModelState.IsValid)
            {
                student1.hobbies = fc["hobb"].ToString(); 
                db.Entry(student1).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student1);
        }

        // GET: student1/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            student1 student1 = db.student1.Find(id);
            if (student1 == null)
            {
                return HttpNotFound();
            }
            return View(student1);
        }

        // POST: student1/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            student1 student1 = db.student1.Find(id);
            db.student1.Remove(student1);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
Posted
Updated 30-Nov-21 17:32pm

1 solution

It's simple. You're trying to use a property of or calling a method of an object that is null (doesn't exist.)

Use the debugger to examine the contents of variables and you'll spot the one that is null pretty easily.

Once you find that, it's up to you to go back through the code and figure out why that variable is null.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900