简体   繁体   中英

ASP.NET MVC remove dynamically created views

I have a view model in my ASP.NET MVC app that holds a List of objects. Each of these objects are visualized using EditorTemplate. Using a dropdown I can add dynamically new object to the List on postback. The problem is when I try to remove a specific element from the list.

public class MyViewModel
{
     public List<MyModel> Items { get; set; }

     public MyViewModel()
     {
          this.Items = new List<MyModel>();
     }
}

public class MyModel
{
    public int Id { get; set; }
    public string Text { get; set; } // I bind this to UI using EditorFor html helper
}

HomeController:

[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
     myViewModels.Items.Add(new MyModel());  // Simulate initializing the Id and Text properties

     return View(myViewModel);
}

Then in Index.cshtml:

if (Model.Items != null)
{
    @Html.EditorFor(m => Model.Items);  // EditorTemplate is used here...
}

So in my template file, called Item.cshtml I have:

@model MVCApp.Models.MyModel

<div>
    @Html.HiddenFor(m => m.Id)
    @Html.EditorFor(m => m.Text)

    <span class="deleteItem" data-item-id="@Model.Id">Delete</span>
</div>

Now I don't know how to process the deletion of the specific item when I click on "Delete". My goal is to have the item deleted from the collection in the controller ('Items' list property of the view model). I can delete the div element using jQuery but the property would not be removed from the 'Items' collection and I would like to avoid jQuery to preserve data integrity between server and client side. I tried to call another action in HomeController called Remove(int? id) where the id parameter is the Id property of 'MyModel', but I need to pass 'MyViewModel' object in Remove action in order to access the 'Items' list, remove the element and then redirect to 'Index' action with the changed collection. How can I achieve that? Thanks!

Update

在此处输入图片说明

If you are looking to do it using. You can submit form using submit button and pass in the id to remove and then calling controller action and code accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM