我正在尝试实施下拉列表,通过一对多关系选择项目。
当表单被POST回控制器时,package.Platform
对象为空,所以我以某种方式搞砸了映射。
/Models/Package.cs
public class Package
{
public int ID {get; set;}
...
public Platform Platform {get; set;}
}
/Models/Platform.cs
public class Platform
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
/Controllers/PackagesController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(
[Bind(Include = "ID,Name,Description,Version,Filename,Platform,IsPublished,ReleaseNotesURL")] Package package)
{
if (ModelState.IsValid)
{
package.Version = VersionParser.ParseVersion(package.Filename).ToString();
db.Entry(package).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
PopulatePlatformsDropDownList(package.Platform.ID); //<<-- package.Platform is null
return View(package);
}
...
private void PopulatePlatformsDropDownList(int? selectedPlatform)
{
var platforms = from d in db.Platforms
orderby d.Name
select d;
ViewBag.Platforms = new SelectList(platforms, "ID", "Name", selectedPlatform);
}
/Views/Packages/Edit.cshtml
...
<div class="form-group">
@Html.LabelFor(model => model.Platform, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Platform, (SelectList)ViewBag.Platforms)
@Html.ValidationMessageFor(model => model.Platform, "", new {@class = "text-danger"})
</div>
</div>
...
哪个发出此HTML:
<select id="Platform" name="Platform" class="valid">
<option value="1">Option One</option>
<option value="2">Option Two</option>
</select>
该关系在SQL中保持如下:
CREATE TABLE [dbo].[Packages](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
...
[Customer_ID] [int] NULL,
[Platform_ID] [int] NULL
...
CREATE TABLE [dbo].[Platforms](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL
(为简洁省略了FK)
因此,我需要正确地获取package.Platform
值,使用Edit()
PackagesController
方法获取它,并将其保存。