首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC表单DropDownListFor

MVC表单DropDownListFor
EN

Stack Overflow用户
提问于 2021-01-12 22:06:02
回答 1查看 44关注 0票数 0

在我看来,我正在构建一个表单,其中用户从国家/地区列表中选择一个国家/地区。我收到关于对象引用未设置为对象实例的错误信息。我是不是遗漏了什么?

代码语言:javascript
复制
                    @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)

模型

代码语言:javascript
复制
 [Required]
        public int? selectedCountryId{ get; set; }

错误

代码语言:javascript
复制
System.NullReferenceException: 'Object reference not set to an instance of an object.'

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

动作方法

代码语言:javascript
复制
 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);
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-12 22:38:24

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

代码语言:javascript
复制
[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添加到模型中,或者为way2的此视图创建Dto,则需要从ViewBag绑定dropdown,而不是使用ListOfCountries作为属性

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65685547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档