Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC Form DropDownListFor

In my view I am building a form where the user select a country from a list of Countries.I get this error about Object reference not set to an instance of an object. Is there anything I am missing?

                    @Html.DropDownListFor(
                            x => x.selectedCountryId,
                            new SelectList(Model.ListOfCountries, "Value", "Text"),
                            "-- please select a Country--",
                            new { id = "ddlCountry", @class = "form-control" }
                    )
                    @Html.ValidationMessageFor(x => x.selectedCountryId)

Model

 [Required]
        public int? selectedCountryId{ get; set; }

Error

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

System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.

Action Method

 public ActionResult Create(RequestFormViewModel model)
        {
            if (!ModelState.IsValid)
            {
                
            }

            return View(TemplateName, "");

    public ActionResult Index()
    {
        RequestFormViewModel  result = new RequestFormViewModel ();

        try
        {
            var FormInfo = GetFormInfo();

            if (FormInfo != null)
            {
                result = FormInfo;


            }
        }
        catch (Exception e)
        {

        }

        return View(TemplateName, result);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your action methods should be like below

[HttpGet]
    public IActionResult Create()
    {
        //Way 1
        RequestFormViewModel model = new RequestFormViewModel();
        model.ListOfCountries = //Select from DB or Whatever
        return View(model);

        //Way 2
        ViewBag.ListOfCountries = //Select from DB or Whatever
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(RequestFormViewModel model)
    {
        if (ModelState.IsValid)
        {
        }
        return View(model);
    }

and for view if you will use way 1 so you need to add ListOfCountries as [NotMapped] to your model or create Dto for this view for way2 you need to bind dropdown from ViewBag instead of using ListOfCountries as a property


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...