5

How can I BindAttribute Include or Exclude nested properties in my controller?

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.

Satpal
  • 132,252
  • 13
  • 159
  • 168
David Board
  • 349
  • 3
  • 12

1 Answers1

0

According to this answer, you could do something like:

[Bind(Include="Name, ServiceID")]
public class Stream
{
...
}

and then

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Stream, SelectedService")] StreamCreateVM viewModel)
{
...
}
Community
  • 1
  • 1
Ilya Luzyanin
  • 7,910
  • 4
  • 29
  • 49
  • Thanks, but I have other actions in the controller that need to Bind to different properties, so this suggestion would preclude that. – David Board Oct 31 '13 at 14:52