locked
SelectList Null on Post Back - RRS feed

  • Question

  • User2005610433 posted

    Hello, I have seen a few threads on this and I've tried to modify the View and the View Model and the Controller several different ways.

    The Get is OK, but the Post is not as I get this error.

    NullReferenceException: Object reference not set to an instance of an object.

    AspNetCore.Views_Question_Create.<ExecuteAsync>b__29_0() in Create.cshtml

    asp-items=@Model.TestGroups

    Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
    Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
    Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
    AspNetCore.Views_Question_Create.ExecuteAsync() in Create.cshtml

    <h1>@ViewData["Title"]</h1>

    Microsoft.AspNetCore.Mvc.Razor.RazorView.

    ViewModel

    using Microsoft.AspNetCore.Mvc.Rendering;
    using System;
    using System.Collections.Generic;

    namespace QA_Project.Models
    {
    public class QuestionCreateViewModel
    {


        public int TestGroup { get; set; }

        public List<SelectListItem> TestGroups { get; set; }


        public int TestArea { get; set; }

        public List<SelectListItem> TestAreas { get; set; }

        public string Description { get; set; }


        public DateTime DateAdded { get; set; }

    }


    }

    View CSHTML

    @model QuestionCreateViewModel
    
    <h1>@ViewData["Title"]</h1>
    
    <form role="form" asp-controller="Question" asp-action="Create" method="post" class="mt-3">
    
        <div class="form-group row">
            <label asp-for="TestGroup" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <select class="custom-select mr-sm-2"
                        asp-for="TestGroup"
                        asp-items=@Model.TestGroups
                   
                        >
                    <option value="">Select</option>
                </select>
                <span class="text-danger" asp-validation-for="TestGroup"></span>
    
            </div>
        </div>
    
    
        <div class="form-group row">
            <label asp-for="TestArea" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <select class="custom-select mr-sm-2" 
                        asp-for="TestArea" 
                        asp-items=@Model.TestAreas
                        
                        >
                    <option value="">Select</option>
                </select>
                <span class="text-danger" asp-validation-for="TestArea"></span>
            </div>
    
        </div>
    
        <div class="form-group row">
            <label class="col-form-label col-sm-2" asp-for="Description"></label>
            <div class="col-sm-10">
                <textarea rows="5" class="form-control textarea" asp-for="Description"></textarea>
            </div>
        </div>
        <div class="text-danger" asp-validation-summary="All"></div>
    
        <div class="row">
            <div class="col-sm-2"></div>
    
            <div class="col-sm-10">
                <button asp-controller="Question" asp-action="Index" class="btn btn-dark">Back</button>
                <input  class="btn btn-primary" type="submit"/>
            </div>
        </div>
    
    </form>



    Controller - Note I did not complete the post action because I am not getting results

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using QA_Project.Models;
    using QA_Project.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace QA_Project.Controllers
    {
        public class QuestionController : Controller
        {
            private readonly IQuestionRepository _questionRepository;
            private readonly ITestGroupRepository _testGroupRepository;
            private readonly ITestAreaRepository _testAreaRepository;
    
            public QuestionController(IQuestionRepository questionRepository, 
                                      ITestGroupRepository testGroupRepository, 
                                      ITestAreaRepository testAreaRepository)
            {
                _questionRepository = questionRepository;
                _testGroupRepository = testGroupRepository;
                _testAreaRepository = testAreaRepository;
            }
            public IActionResult Index()
            {
                var model = _questionRepository.GetAllQuestions();
    
                return View(model);
            }
    
            public IActionResult Details(int id)
            {
                QuestionDetailsViewModel questionDetailsViewModel 
                    = new QuestionDetailsViewModel()
                {
                    Question = _questionRepository.GetQuestion(id)
                };
    
                return View(questionDetailsViewModel);
            }
    
            [HttpGet]
            public IActionResult Create()
            {
                var model = new QuestionCreateViewModel();
    
                //  model.TestAreas = _testAreaRepository.GetTestAreas().ToList();
    
                //model.TestGroups = _testGroupRepository.GetTestGroups().ToList();
    
                model.TestAreas =  new List<SelectListItem>(
                                   new SelectList(_testAreaRepository.GetTestAreas(), "TestAreaId", "TestAreaName"));
    
                model.TestGroups = new List<SelectListItem>(
                                   new SelectList(_testGroupRepository.GetTestGroups(), "TestGroupId", "TestGroupName"));
    
                //new SelectList(_testGroupRepository.GetTestGroups(),"TestGroupId","TestGroups");
               
    
                    //new SelectList(_testAreaRepository.GetTestAreas(), "TestAreaId", "TestAreaName");
    
                ViewData["Title"] = "Create Question";
                return View(model);
            }
    
            [HttpPost]
            public IActionResult Create(QuestionCreateViewModel model)
            {
                 
                
                //if (ModelState.IsValid)
                //{
                //    model.DateAdded = DateTime.Now;
                //    return View();
                //    //Question newquestion = _questionRepository.Add(model);
                //    //return RedirectToAction("Details", new { id = newquestion.QuestionId });
                //}
                return View();
            }
    
            [HttpGet]
            public IActionResult Edit(int id)
            {
                Question question = _questionRepository.GetQuestion(id);
    
                ViewData["Title"] = "Edit Question";
                return View(question);
            }
    
            [HttpPost]
            public IActionResult Edit(Question model)
            {
                if (ModelState.IsValid)//verifies if validation passes
                {
    
                    Question editQuestion = _questionRepository.Update(model);
                    return RedirectToAction("Index");
                }
                return View();
            }
        }
    }
    

    Thursday, September 5, 2019 4:29 AM

Answers

  • User2005610433 posted

    Thanks, actually I resolved my own problem.  I was redirecting to the wrong view.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 4:18 AM

All replies

  • User2005610433 posted

    Sorry I am not sure how to format the code in this site.

    Thursday, September 5, 2019 4:32 AM
  • User-821857111 posted

    Click the Insert/Edit Code Sample toolbar icon {;} and paste your formatted code in the modal that appears

    Thursday, September 5, 2019 9:20 AM
  • User2005610433 posted

    Thanks!

    Friday, September 6, 2019 4:16 AM
  • User711641945 posted

    Hi lukasamen,

    I could not reproduce the issue by using your code.I suggest that you could share your ITestGroupRepository,ITestAreaRepository and the implement class.

    Here is my workaroud:

    1.Model:

    public class Area
    {
        public int TestAreaId { get; set; }
        public string TestAreaName { get; set; }
    }
    public class Group
    {
        public int TestGroupId { get; set; }
        public string TestGroupName { get; set; }
    }
    

    2.Interface and implement class:

    public interface ITestAreaRepository
    {
        List<Area> GetTestAreas();
    }
    public class TestAreaRepository : ITestAreaRepository
    {
        public List<Area> GetTestAreas()
        {
            var areas = new List<Area>() {
                new Area(){ TestAreaId=1,TestAreaName="ccc"},
                new Area(){ TestAreaId=2,TestAreaName="ddd"}
            };
            return areas;
        }
    }
    public interface ITestGroupRepository
    {
        List<Group> GetTestGroups();
    }
    public class TestGroupRepository : ITestGroupRepository
    {
        public List<Group> GetTestGroups()
        {
            var groups = new List<Group>() {
                new Group(){ TestGroupId=1,TestGroupName="aa"},
                new Group(){ TestGroupId=2,TestGroupName="bb"}
            };
            return groups;
        }
    }
    

    3.Controller:

    [HttpGet]
    public IActionResult Create()
    {
        //by using your code...
    }

    4.Result:

    Best Regards,

    Rena

    Friday, September 6, 2019 5:42 AM
  • User2005610433 posted

    Thanks, actually I resolved my own problem.  I was redirecting to the wrong view.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 4:18 AM