Proper Einreichung der Formulare mit automatisch generierten Kontrollen
-
05-07-2019 - |
Frage
Auf der Grundlage von: MVC Html.CheckBox und Formular Ausgabe
Lassen Sie sich folgendes Beispiel. Ausblick:
<% using(Html.BeginForm("Retrieve", "Home")) %>
<% { %>
<%foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(""+app.ApplicationId )%></td>
</tr>
<%} %>
<input type"submit"/>
<% } %>
Controller:
List<app>=newApps; //Database bind
for(int i=0; i<app.Count;i++)
{
var checkbox=Request.Form[""+app[i].ApplicationId];
if(checkbox!="false")// if not false then true,false is returned
}
Vorgeschlagene Lösung war über die manuelle Analyse von Request.Form, die für mich aus MVC-Konzept scheint. Es macht das Problem beim Unit-Tests dieser Controller-Methode. In diesem Fall muss ich Mock Request.Form Objekt statt einige Ansichtsmodell übergeben als Eingabe param erzeugen.
F: Gibt es eine andere Lösung von Formen wie diese Vorlage, so dass Ansichtsmodell Objekt, mit Sammlung der eingereichten Kontrollen als Eingang param gebene Methode zur Steuerung
Zum Beispiel:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
oder
public ActionResult Retrieve(AppList<App> applist)
etc
Lösung
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
Ausblick:
<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
<%foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(String.Format("appList[{0}].AProperty", app.ApplicationId) %></td>
</tr>
<% } %>
<input type"submit" />
<% } %>
AKTUALISIERT:
Wenn ApplicationId ist ein Schlüssel von der DB ist es besser AppList<App>
als Action-Parameter zu verwenden. Dann würde Ihre Form suchen, wie:
<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
<% var counter = 0; %>
<% foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(String.Format("appList[{0}].Key", counter), app.ApplicationId) %></td>
<!-- ... -->
<td><%=Html.Input(String.Format("appList[{0}].Value.SomeProperty1", counter), app.SomeProperty1) %></td>
<td><%=Html.Input(String.Format("appList[{0}].Value.SomePropertyN", counter), app.SomePropertyN) %></td>
<% counter = counter + 1; %>
</tr>
<% } %>
<input type"submit" />
<% } %>