從我明白,你想在C#代碼提交給服務器的表單元素的ID。我不認爲這是可能的(服務器不會提交該ID),但只需稍作更改,您就可以獲得所需的結果。
雖然我不得不作出一些假設 - 如果假設不是很正確,我會盡量對此進行評論,我會盡力滿足。
首先,我將假設您的變量「productList」是一個IList<>
,它具有兩個屬性「articleNumber」和「article」。讓我們把這種類型Article
,而且會是這樣的形式:
public class Article
{
public string article { get; set; }
// I'm assuming it's just a string here
public string articleNumber { get; set; }
}
我也假設這不是你傳遞給這個視圖模型或視圖模型(如果有的話)的一部分,所以我贏了」在這裏使用任何HtmlHelpers。
你可以做的CSHTML文件如下:
@for (int i; i < productList.Count; i++)
{
<input name="[i].articleNumber" type="hidden" value="@item.articleNumber" />
<input name="[i].article" type="text"/>
}
而不是使用一個ID,我用一個隱藏字段。這樣,文章編號將隨文章一起提交。 [i]
參數告訴MVC對象是列表的一部分,並且articleNumber
和article
是同一對象的一部分,因此將數字和文章保持在一起,假設接收對象具有這些字段(我們假定它)。有關模型綁定到列表的更多信息,請參閱this article by Phill Haack。然後
你的控制器動作將成爲:
public ActionResult bestelProducten(IList<Article> articles)
{
foreach (Article a in articles)
{
DialogResult d = TopMostMessageBox.Show(string.Format("Article Number: {0} - Article Order: {1}", a.articleNumber, a.article), "Test", MessageBoxButtons.OK);
}
return View();
}
控制器中articles
參數將自動綁定到你的命名[i].
參數列表。
我已經完成了我的頭頂,所以它可能需要一些調整 - 但我希望這是你在找什麼。
更新:首先,我有兩個參數的錯誤的方式圍繞在for循環 - 修正了!
其次,希望我現在可以更全面地幫助你!請注意,在上面的代碼中,您可以將IList
替換爲List
,IList
是實現List
的接口。現在我會繼續使用List
。
我明白了文本框的作用。所以,你的Article
實際上有三個字段,第三個整數值articleOrder。在這種情況下,我會做到這一點:
1)創建一個ArticleOrderModel
對象,看起來像這樣:
public class ArticleOrderModel
{
// This is the number of your article
public int ArticleNumber { get; set; }
// This is the order it appears in
public int ArticleOrder { get; set; }
}
2)在你看來,設置您對這樣的循環(假設你使用productList的,你的問題本來說明):
@for (int i; i < productList.Count; i++)
{
<!-- Add your HtmlHelpers here as you mention -->
@Html.DisplayFor(x => x[i].articleNumber);
@Html.DisplayFor(x => x[i].article);
<!-- As you are submitting to the model, you need to create form
elements that will submit to it. The first line provides the article
number, the second is your textbox -->
<input name="[i].articleNumber" type="hidden" value="@item.articleNumber" />
<input name="[i].articleOrder" type="text"/>
}
3)設置你的控制器是這樣的:
public ActionResult bestelProducten(List<ArticleOrderModel> model)
{
// Get your article list out of storage here
foreach (ArticleOrderModel a in model)
{
// Here, I recommend that you put the order into the original Article objects,
// I just will leave the original code here.
DialogResult d = TopMostMessageBox.Show(string.Format("Article Number: {0} - Article: {1}", a.articleNumber, a.articleOrder), "Test", MessageBoxButtons.OK);
}
return View();
}
我爲控制器操作使用了一個單獨的模型,因爲我得到了您只想顯示文章文本的印象,並且您想要文章訂單。我選擇的模型只是獲取您需要的數據。
如果你想編輯同一個頁面上的文章全文爲好,然後更改控制器的參數是一個Article
,只是做在您的視圖:
@for (int i; i < productList.Count; i++)
{
<!-- Add your HtmlHelpers here as you mention -->
@Html.DisplayFor(x => x[i].articleNumber);
@Html.HiddenFor(x => x[i].articleNumber);
@Html.EditorFor(x => x[i].article);
@Html.EditorFor(x => x[i].articleOrder);
}
在這種情況下,你不需要打擾ArticleOrderModel
我必須回答這個問題,因爲我的評論無法在此框。對不起=(答案是給你的 –