Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Binding to a complex ViewModel

$
0
0

I have a model class called linksmvccore.  It's just a link number with IDs pointing to data in 2 other tables

    [Table("linksmvccore")]
    public partial class Linksmvccore
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int LinkNumber { get; set; }
        [Column("BagID", TypeName = "int(11)")]
        public int? BagId { get; set; }
        [Column("PersonID", TypeName = "int(11)")]
        public int? PersonId { get; set; }
    }

I also have a compound ViewModel

        public class AllLinkViewModel
        {
            public Bagsmvc Bag { get; set; }
            public Peoplemvc Person { get; set; }
            public Linksmvccore Link { get; set; }
            public List<Peoplemvc> People { get; set; }
            public List<Bagsmvc> Bags{ get; set; }
            public List<Linksmvccore> Links { get; set; }
}

And here's the edit view

@model BagContext.AllLinkViewModel

@{
    ViewData["Title"] = "Edit";
}<h1>Edit</h1><div class="row"><div class="col-md-4"><form asp-action="Edit"><input type="hidden" asp-for="Link.LinkNumber" /><div class="form-group"><label asp-for="Link.BagId" class="control-label"></label><input asp-for="Link.BagId" class="form-control" /></div><div class="form-group"><label asp-for="Link.PersonId" class="control-label"></label><input asp-for="Link.PersonId" class="form-control" /></div><input type="submit" value="Save" asp-route-everything="@Model" class="btn btn-primary" /></div></form></div></div>

I can pass the model to the Edit controller successfully like this

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, AllLinkViewModel alvm) {

...

}

But I am unable to prevent overbinding

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id,      
               [Bind("Link.LinkNumber,BagId,Link_PersonId")] AllLinkViewModel alvm)

I've tried 3 different ways of Binding but none of them will bind with the model.  How can I prevent overbinding here?


Viewing all articles
Browse latest Browse all 9386

Trending Articles