التقديم الصحيح للنماذج مع عناصر التحكم التي تم إنشاؤها تلقائيًا
-
05-07-2019 - |
سؤال
مرتكز على:مشكلة MVC Html.CheckBox وإرسال النموذج
دعونا نفكر في المثال التالي.منظر:
<% using(Html.BeginForm("Retrieve", "Home")) %>
<% { %>
<%foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(""+app.ApplicationId )%></td>
</tr>
<%} %>
<input type"submit"/>
<% } %>
مراقب:
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
}
كان الحل المقترح يتعلق بالتحليل اليدوي لـ Request.Form الذي يبدو بالنسبة لي خارج مفهوم MVC.إنه يجعل المشكلة أثناء اختبار الوحدة لطريقة التحكم هذه.في هذه الحالة أحتاج إلى إنشاء كائن Request.Form وهمي بدلاً من نموذج ViewModel الذي تم تمريره كمعلمة إدخال.
س:هل هناك حل آخر لإرسال نماذج مثل هذا، بحيث يتم تمرير كائن ViewModel، الذي يحتوي على مجموعة من عناصر التحكم المقدمة، كمعلمة إدخال إلى طريقة التحكم؟
على سبيل المثال:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
أو
public ActionResult Retrieve(AppList<App> applist)
إلخ
المحلول
مراقب:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
منظر:
<% 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" />
<% } %>
محدث:
إذا كان ApplicationId مفتاحًا من قاعدة البيانات فمن الأفضل استخدامه AppList<App>
كمعلمة العمل.ثم سيبدو النموذج الخاص بك على النحو التالي:
<% 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" />
<% } %>
لا تنتمي إلى StackOverflow