簡體   English   中英

提交具有非順序索引/位置的列表/集合

[英]Submitting a list/Collection with non-sequential indices/positions

我有一個包含List的viewmodel,例如:

class School
{
    public List<Student> Students { get; set; }
}
class Student
{
    public int Id { get; set; } 
    public String Name { get; set; } 
}

我有一份表格,我提交了與單一學校相關的多個學生信息。 現在我可以從表單中添加/刪除單個學生。

添加工作正常,但我的問題和我的問題與刪除學生有關。

讓我用一個例子解釋一下:

假設我添加了3名學生,然后名稱和ID將以這種方式綁定到模型:

Students[0].Id = "1"

Students[0].Name = "Student A"

Students[1].Id = "2"

Students[1].Name = "Student B"

Students[2].Id = "3"

Students[2].Name = "Student C"

如果我保存這個就可以了。 但是讓我說我​​刪除Id =“2”的學生。提交正在發生的事情是只有id =“1”的學生被綁定並且在刪除索引后休息(即id =“3”的學生)是沒有綁定。

我的問題是:刪除id =“2”之后是否可以綁定id =“3”? 或者以適當的方式綁定/提交帶有跳過索引的列表是可能的。

我在stackoverflow本身找到了下面提到的文章,但我可以從中推斷出有點矛盾,或者我可能沒有正確理解它們。

跳過不可能

跳過可能

我不善於解釋問題。 所以請告訴我是否可以添加任何內容以使其更具描述性。
謝謝。 示例刪除代碼: 刪除Js代碼的小提琴

我發布此答案以供將來參考其他任何有同樣疑慮的人參考。

所以如果你有這樣的集合:

public class Book {
    public string Title { get; set; }
    public string Author { get; set; }
    public DateTime DatePublished { get; set; }
}

//Action method on HomeController
public ActionResult UpdateProducts(ICollection<Book> books) {
    return View(books);
}

添加3本書后,您的表單如下所示:

<form method="post" action="/Home/Create">

    <input type="text" name="[0].Title" value="Curious George" />
    <input type="text" name="[0].Author" value="H.A. Rey" />
    <input type="text" name="[0].DatePublished" value="2/23/1973" />

    <input type="text" name="[1].Title" value="Code Complete" />
    <input type="text" name="[1].Author" value="Steve McConnell" />
    <input type="text" name="[1].DatePublished" value="6/9/2004" />

    <input type="text" name="[2].Title" value="The Two Towers" />
    <input type="text" name="[2].Author" value="JRR Tolkien" />
    <input type="text" name="[2].DatePublished" value="6/1/2005" />

    <input type="submit" />
</form>

現在,如果你們想要添加刪除功能,使你的表單可能包含非順序條目,那么可以這樣做:

<form method="post" action="/Home/Create">

    <input type="hidden" name="products.Index" value="cold" />
    <input type="text" name="products[cold].Name" value="Beer" />
    <input type="text" name="products[cold].Price" value="7.32" />

    <input type="hidden" name="products.Index" value="123" />
    <input type="text" name="products[123].Name" value="Chips" />
    <input type="text" name="products[123].Price" value="2.23" />

    <input type="hidden" name="products.Index" value="caliente" />
    <input type="text" name="products[caliente].Name" value="Salsa" />
    <input type="text" name="products[caliente].Price" value="1.23" />

    <input type="submit" />
</form>

在上面的示例中,我們為每個需要綁定到列表的項提供帶有.Index后綴的隱藏輸入。 這將為模型綁定器提供一個很好的索引集合,以便在綁定到列表時查找。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM