微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MVC 表单 DropDownListFor

如何解决MVC 表单 DropDownListFor

在我看来,我正在构建一个表单,用户可以在其中从国家列表中选择一个国家。我收到有关未将对象引用设置为对象实例的错误。有什么我遗漏的吗?

                    @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)

型号

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

错误

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

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

动作方法

 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);
    }

解决方法

您的操作方法应该如下所示

[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);
    }

如果您将使用方式 1,那么您需要将 ListOfCountries 作为 [NotMapped] 添加到您的模型或为此视图创建 Dto 对于 way2,您需要从 ViewBag 绑定下拉列表,而不是使用 ListOfCountries 作为属性

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。