BindAttribute, Exclude nested properties for complex types
Posted
by
David Board
on Stack Overflow
See other posts from Stack Overflow
or by David Board
Published on 2013-10-30T15:51:22Z
Indexed on
2013/10/30
15:53 UTC
Read the original article
Hit count: 507
I have a 'Stream' model:
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; }
}
For the 'create' view for this model, I have made a view model to pass some additional information to the view:
public class StreamCreateVM
{
public Stream Stream { get; set; }
public SelectList ServicesList { get; set; }
public int SelectedService { get; set; }
}
Here is my create post action:
[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);
}
Now, this all works, apart from the [Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")]
bit. I can't seem to Include or Exclude properties within a nested object.
© Stack Overflow or respective owner