简体   繁体   English

ASP.NET MVC删除动态创建的视图

[英]ASP.NET MVC remove dynamically created views

I have a view model in my ASP.NET MVC app that holds a List of objects. 我的ASP.NET MVC应用程序中有一个视图模型,其中包含一个对象列表。 Each of these objects are visualized using EditorTemplate. 这些对象的每一个都使用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: 然后在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: 因此,在名为Item.cshtml的模板文件中,我有:

@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. 我可以使用jQuery删除div元素,但不会从'Items'集合中删除该属性,并且我想避免jQuery保留服务器端和客户端之间的数据完整性。 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. 我试图在HomeController中调用另一个动作,称为Remove(int?id),其中id参数是“ MyModel”的Id属性,但是我需要在Remove动作中传递“ MyViewModel”对象才能访问“项”列表,删除元素,然后使用更改后的集合重定向到“索引”操作。 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. 您可以使用“提交”按钮提交表单,并传递ID以删除,然后相应地调用控制器操作和代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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