Krish
Krish

Reputation: 307

Viewbag: Cannot perform runtime binding on a null reference error

Controller

  [HttpPost]
        public ActionResult AddEmployee(EmpModel emp)
        {
            try
            {
                if(ModelState.IsValid)
                {
                    EmpRepository empRepository = new EmpRepository();
                    empRepository.AddEmployee(emp);
                    ViewBag.Message("Employee Record Successfully");
                }                

                return View(new EmpModel());
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

View

<div class="col-md-offset-2 col-md-10">
    @ViewBag.Message
</div>

Getting the exception as I mentioned in the title of this problem. What am I missing here?

Upvotes: 0

Views: 714

Answers (2)

Karan Ekkawala
Karan Ekkawala

Reputation: 327

The first thing that fills the value to viewbag using below syntax

ViewBag.Message = "put your content";

And 1 more thing as per your code the viewbag exists only when your model state validation fulfills so make sure that you have checked null on the view (.cshtml) before using it.

Upvotes: 2

Krish
Krish

Reputation: 307

Just changed the following code

ViewBag.Message("Employee Record Successfully");

to

ViewBag.Message = "Employee Record Successfully";

Upvotes: 1

Related Questions