如何BindAttribute在控制器中包含或排除嵌套属性?
我有一个'Stream'模型:
public class Stream
{
public int ID { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Stream name cannot be longer than 50 characters.")]
public string Name { get; set; }
[Required]
[DataType(DataType.Url)]
public string URL { get; set; }
[Required]
[Display(Name="Service")]
public int ServiceID { get; set; }
public virtual Service Service { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Monitor> Monitors { get; set; }
public virtual ICollection<AlertRule> AlertRules { get; set; }
}
对于此模型的“创建”视图,我创建了一个视图模型以将一些其他信息传递给视图:
public class StreamCreateVM
{
public Stream Stream { get; set; }
public SelectList ServicesList { get; set; }
public int SelectedService { get; set; }
}
这是我的创建后期操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")] StreamCreateVM viewModel)
{
if (ModelState.IsValid)
{
db.Streams.Add(viewModel.Stream);
db.SaveChanges();
return RedirectToAction("Index", "Service", new { id = viewModel.Stream.ServiceID });
}
return View(viewModel);
}
现在,除了[Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")]
位之外,这一切都有效。我似乎无法在嵌套对象中包含或排除属性。
答案 0 :(得分:0)
根据this answer,您可以执行以下操作:
[Bind(Include="Name, ServiceID")]
public class Stream
{
...
}
然后
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Stream, SelectedService")] StreamCreateVM viewModel)
{
...
}