Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...