将下拉列表值发送回变量 MVC 4

本文关键字:变量 MVC 下拉列表 | 更新日期: 2023-09-27 18:30:37

嗨,我有一个带有特定 id 的作业表

id   title
1    Manager
2    Engineer
3    IT 

我创建了一种方法,以便能够使用此表和数据从数据库中加载这些值。

这是我的模型

[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public IEnumerable<SelectListItem> jobTitle { get; set; }

这是我的控制器

public void loadDropDown()
        {
            JobModel selectedJob = new JobModel();
            reviewlogsEntities db = new reviewlogsEntities();
            IEnumerable<SelectListItem> type = db.types.Select(m => new SelectListItem
            {
                Value = SqlFunctions.StringConvert((double)m.id),
                Text = m.title

            });

            ViewBag.JobTitle = type;
        }
        [HttpGet]
        public ActionResult DisplayJobTitle()
        {
            if (Request.IsAuthenticated)
            {
                loadDropDown();
                return View();

            }       
            else
            {
                return RedirectToAction("index", "home");
            }
        }
        [HttpPost]
        public ActionResult DisplayJobTitle(JobModel curJob)
        {

            loadDropDown();
             if (ModelState.IsValid)
             {
                 return View();
             }
             else
             {
                 ModelState.AddModelError("", "Looks like there was an error                     with your job title, please make sure a job title is selected.");
             }
              return View();
        }

最后,我的观点是这样的:

@Html.ValidationSummary(true, "Please try again.")
@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.type)
    @Html.DropDownList("JobTitle")
    <input class="submitButton" type="submit" value="Show Job Info" style="margin-left:126px;margin-bottom: 20px;" />
}

看到问题是我的模型中的变量 jobTitle 是空的,因为我从不给它一个值,而且因为我没有给它一个值,所以表单认为它没有填写,因为它必须是必需的并且不会正确提交。我的问题是,提交表单时,如何将用户选择作为其职务的任何值返回给 jobTitle 变量,这样我就不会收到提交失败的情况。

将下拉列表值发送回变量 MVC 4

模型应接受选定的值而不是项目的集合:

[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int jobTitle { get; set; }
您需要

一个属性来映射模型中的选定值,例如:

[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int SelectedjobTitle { get; set; }

然后在您的视图中:

@Html.DropDownList("SelectedJobTitle",ViewBag.JobTile as IEnumerable<SelectListItem>)

使用 DropDownList:

@Html.DropDownListFor(model => model.JobTitle, Model.Jobs)

在您的模型上:

[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int JobTitle { get; set; }
public IEnumerable<SelectListItem> Jobs { get; set; } 

不要忘记填写控制器上的"作业"。