ASP.NET 核心 5 MVC:ArgumentNullException:值不能为空。 (参数'items')
ASP.NET Core 5 MVC: ArgumentNullException: Value cannot be null. (Parameter 'items')
我在创建页面的 GET 方法中有这个列表:
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
显示是这样的:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
在模型中 Prepared_By
是一个字符串。
在创建页面上,当我点击提交时,出现以下错误:
ArgumentNullException: Value cannot be null. (Parameter 'items')
指向
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
关于这个问题,我发现有几件事非常有趣。首先,在创建页面的 POST 方法中,如果我打印 Prepared_By
的值,它总是打印正确的名称:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
}
然而,当我尝试在 if(ModelState.IsValid)
中第二次打印它时,它不起作用。
还有什么有趣的是,我在不同的创建页面中使用了这个完全相同的列表并且它工作得很好:
<div class="form-group col-md-3">
<label class="control-label">DSN PM</label>
<select asp-for="DSN_PM" name="DSN_PM" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="DSN_PM" class="text-danger"></span>
</div>
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Project_Name,County,Memo_Date,From,Authorization,DSN_PM,History,History_PM,Review_Exempt_H,SHPO_Approval_H,Archaeology,Archaeology_PM,Review_Exempt_A,SHPO_Approval_A,ESA_Key,Crayfish,Crayfish_Habitat_Assessment,NLEB_4D,USFWS,USFWS_Type,Mussel_Habitat,Mussel_Stream,Within_Airport,ToPo_Quad_Name,Bat_Habitat,Bars,Coordinates,Natural_Resources_Notes,Adduser,Date_Added,Crayfish_Notes,Mussel_Notes")] Project_Screen project_Screen)
{
if (ModelState.IsValid)
{
project_Screen.Adduser = User.Identity.Name;
project_Screen.Date_Added = DateTime.Today;
_context.Add(project_Screen);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(project_Screen);
}
在第二个示例中,我在 GET 方法中以完全相同的方式创建了列表,而且我从未遇到过这个问题。可能是什么问题?
编辑:问题更新
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
return View(typeOne);
}
查看:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users,"Id","Name"))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
这里有几个问题。首先,问题依然存在,没有任何改变。我不确定视图的代码是否完全正确,但它给了我一个 Object reference not set to an instance of an object.
错误,但我真的不知道它指向什么。我也不知道你为什么要添加 ID,因为我不会在任何地方使用它,也不需要。
编辑 2:
获取方法:
// GET: TypeOnes/Create
public IActionResult Create()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = assessments;
List <SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List <SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
return View();
}
如果我在 POST 方法中重新创建每个列表,那么我不会在任何地方出现任何错误,它只是将我发送回创建页面并且不执行数据库插入
POST方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
var prep = typeOne.Prepared_By;
typeOne.Prepared_By = prep;
_context.Add(typeOne);
await _context.SaveChangesAsync();
//Send all History and Archaeology Unit Leaders an email
List<string> histAndArchLeads = (from s in _context.NR_Users
where s.User_Type == "Unit Leader" && s.Unit == "History" || s.Unit == "Archaeology"
select s.Email_Address).ToList();
foreach(var email in histAndArchLeads)
{
SendEmail(email);
}
//Send an email to Traci if project needs a Mussel or Crayfish habitat assessement (Natural resources Lead)
if (Assessment != "No" )
{
SendEmail("Cole.k.perry@wv.gov");
}
//Send an email to bat lady if project needs a bat habitat assessement
if (Bat)
{
SendEmail("Cole.k.perry@wv.gov");
}
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
你能检查一下 ASP.NET <form />
元素吗?它应该是这样的:
<form asp-controller="MyController" asp-action="MyAction" method="post">
<!-- Your controls and etc -->
</form>
First of all, in the POST method for the create page if I print the value of Prepared_By it always prints the correct name
当然它会打印出正确的值,因为你post数据到后台成功了。但是你需要知道下拉填充的数据不是由 Prepared_By
存储的。它使用 asp-items="@(new SelectList(ViewBag.users))"
存储值。您没有在 post 方法中设置 ViewBag.users
,这就是为什么当您 post 返回时会出现 ArgumentNullException
错误。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
//return View("ViewName", typeOne);
//if you return Create.cshtml, no need specify the view name
return View(typeOne);
}
按照你的第二种方式,一定要调试你的代码,看看它什么时候运行。如果您在填充下拉列表时不为 ViewBag.users
设置值,则不可能。如有不同请慎重
这是一个完整的简单工作演示:
型号:
public class Test
{
public string Id{ get; set; }
public string Name { get; set; }
}
public class TestModel
{
public string Prepared_By { get; set; }
}
查看(Create.cshtml):
此外,您需要使用 public SelectList(IEnumerable items, string dataValueField, string dataTextField);
来显示下拉菜单的正确值和文本。
model TestModel
<form method="post">
<select asp-for="Prepared_By" name="Prepared_By" class="form-control"
asp-items="@(new SelectList(ViewBag.users,"Id","Name"))"></select>
<input type="submit" value="Post" />
</form>
控制器:
[HttpGet]
public IActionResult Create()
{
var data = new List<User>()
{
new User(){ Id="1",Name= "aa" },
new User(){ Id="2",Name= "bb" },
new User(){ Id="3",Name= "cc" }
};
ViewBag.users = data;
return View();
}
[HttpPost]
public IActionResult Create(TestModel model)
{
ViewBag.users = new List<Test>()
{
new Test(){ MenuCategoryId="1",Content= "aa" },
new Test(){ MenuCategoryId="2",Content= "bb" },
new Test(){ MenuCategoryId="3",Content= "cc" }
};
return View(model);
}
我明白了。我将下拉列表抽象为第三种方法 DropDowns()
,然后在 GET 和 POST 方法中调用该方法:
public void DropDowns()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
}
获取:
// GET: TypeOnes/Create
public IActionResult Create()
{
DropDowns();
return View();
}
POST:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
DropDowns();
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
它开始工作了。
我在创建页面的 GET 方法中有这个列表:
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
显示是这样的:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
在模型中 Prepared_By
是一个字符串。
在创建页面上,当我点击提交时,出现以下错误:
ArgumentNullException: Value cannot be null. (Parameter 'items')
指向
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
关于这个问题,我发现有几件事非常有趣。首先,在创建页面的 POST 方法中,如果我打印 Prepared_By
的值,它总是打印正确的名称:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
}
然而,当我尝试在 if(ModelState.IsValid)
中第二次打印它时,它不起作用。
还有什么有趣的是,我在不同的创建页面中使用了这个完全相同的列表并且它工作得很好:
<div class="form-group col-md-3">
<label class="control-label">DSN PM</label>
<select asp-for="DSN_PM" name="DSN_PM" class="form-control" asp-items="@(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="DSN_PM" class="text-danger"></span>
</div>
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Project_Name,County,Memo_Date,From,Authorization,DSN_PM,History,History_PM,Review_Exempt_H,SHPO_Approval_H,Archaeology,Archaeology_PM,Review_Exempt_A,SHPO_Approval_A,ESA_Key,Crayfish,Crayfish_Habitat_Assessment,NLEB_4D,USFWS,USFWS_Type,Mussel_Habitat,Mussel_Stream,Within_Airport,ToPo_Quad_Name,Bat_Habitat,Bars,Coordinates,Natural_Resources_Notes,Adduser,Date_Added,Crayfish_Notes,Mussel_Notes")] Project_Screen project_Screen)
{
if (ModelState.IsValid)
{
project_Screen.Adduser = User.Identity.Name;
project_Screen.Date_Added = DateTime.Today;
_context.Add(project_Screen);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(project_Screen);
}
在第二个示例中,我在 GET 方法中以完全相同的方式创建了列表,而且我从未遇到过这个问题。可能是什么问题?
编辑:问题更新
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
return View(typeOne);
}
查看:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="@(new SelectList(ViewBag.users,"Id","Name"))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
这里有几个问题。首先,问题依然存在,没有任何改变。我不确定视图的代码是否完全正确,但它给了我一个 Object reference not set to an instance of an object.
错误,但我真的不知道它指向什么。我也不知道你为什么要添加 ID,因为我不会在任何地方使用它,也不需要。
编辑 2:
获取方法:
// GET: TypeOnes/Create
public IActionResult Create()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = assessments;
List <SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List <SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
return View();
}
如果我在 POST 方法中重新创建每个列表,那么我不会在任何地方出现任何错误,它只是将我发送回创建页面并且不执行数据库插入
POST方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
var prep = typeOne.Prepared_By;
typeOne.Prepared_By = prep;
_context.Add(typeOne);
await _context.SaveChangesAsync();
//Send all History and Archaeology Unit Leaders an email
List<string> histAndArchLeads = (from s in _context.NR_Users
where s.User_Type == "Unit Leader" && s.Unit == "History" || s.Unit == "Archaeology"
select s.Email_Address).ToList();
foreach(var email in histAndArchLeads)
{
SendEmail(email);
}
//Send an email to Traci if project needs a Mussel or Crayfish habitat assessement (Natural resources Lead)
if (Assessment != "No" )
{
SendEmail("Cole.k.perry@wv.gov");
}
//Send an email to bat lady if project needs a bat habitat assessement
if (Bat)
{
SendEmail("Cole.k.perry@wv.gov");
}
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
你能检查一下 ASP.NET <form />
元素吗?它应该是这样的:
<form asp-controller="MyController" asp-action="MyAction" method="post">
<!-- Your controls and etc -->
</form>
First of all, in the POST method for the create page if I print the value of Prepared_By it always prints the correct name
当然它会打印出正确的值,因为你post数据到后台成功了。但是你需要知道下拉填充的数据不是由 Prepared_By
存储的。它使用 asp-items="@(new SelectList(ViewBag.users))"
存储值。您没有在 post 方法中设置 ViewBag.users
,这就是为什么当您 post 返回时会出现 ArgumentNullException
错误。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
//return View("ViewName", typeOne);
//if you return Create.cshtml, no need specify the view name
return View(typeOne);
}
按照你的第二种方式,一定要调试你的代码,看看它什么时候运行。如果您在填充下拉列表时不为 ViewBag.users
设置值,则不可能。如有不同请慎重
这是一个完整的简单工作演示:
型号:
public class Test
{
public string Id{ get; set; }
public string Name { get; set; }
}
public class TestModel
{
public string Prepared_By { get; set; }
}
查看(Create.cshtml):
此外,您需要使用 public SelectList(IEnumerable items, string dataValueField, string dataTextField);
来显示下拉菜单的正确值和文本。
model TestModel
<form method="post">
<select asp-for="Prepared_By" name="Prepared_By" class="form-control"
asp-items="@(new SelectList(ViewBag.users,"Id","Name"))"></select>
<input type="submit" value="Post" />
</form>
控制器:
[HttpGet]
public IActionResult Create()
{
var data = new List<User>()
{
new User(){ Id="1",Name= "aa" },
new User(){ Id="2",Name= "bb" },
new User(){ Id="3",Name= "cc" }
};
ViewBag.users = data;
return View();
}
[HttpPost]
public IActionResult Create(TestModel model)
{
ViewBag.users = new List<Test>()
{
new Test(){ MenuCategoryId="1",Content= "aa" },
new Test(){ MenuCategoryId="2",Content= "bb" },
new Test(){ MenuCategoryId="3",Content= "cc" }
};
return View(model);
}
我明白了。我将下拉列表抽象为第三种方法 DropDowns()
,然后在 GET 和 POST 方法中调用该方法:
public void DropDowns()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
}
获取:
// GET: TypeOnes/Create
public IActionResult Create()
{
DropDowns();
return View();
}
POST:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
DropDowns();
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
它开始工作了。