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.

1 Answer 1

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)
{
...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I have other actions in the controller that need to Bind to different properties, so this suggestion would preclude that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.