[英]Pass bool property value issue to make auto select checkbox using ASP.NET MVC and C#
我想自動選擇打開頁面時名為“ File1”和“ File2”的文件的兩個復選框,它們的工作順序類型為1或2或3。 如果在For循環中找到“ File1”和“ File2”,則在Model中使用屬性布爾類型返回true。 但是,不知何故,其他文件的所有復選框都會自動選中,應該只是“ File1”和“ File2”的復選框。 這是我的代碼:
Web配置
<appsettings>
<add key="JobOrderType" value="1,2,3"/>
</appsettings>
CustomerDocument.cs-我的視圖模型
public class CustomerDocument
{
public bool IncludeInEmail { get; set; }
public long DocumentId { get; set; }
public string DisplayName { get; set; }
public string DocumentPath { get; set; }
public bool IsAutoSelectFile { get; set; }
}
ShowJobTypeController.cs
[HttpGet]
public ActionResult ShowJobType() {
try
{
//Make auto select for File1 and File2 for some certain job order types
List<CustomerCustomers> customerDocuments;
var myQuery = dbTest2.JobOrders.FirstOrDefault(z => z.Id == JobOrderId);
var jobOrderTypeId = new List<int>();
var configJOTypeValues = ConfigurationManager.AppSettings["JobOrderType"].Split(',');
for (var i = 0; i < configJOTypeValues.Length; i++)
{
var IdValue = 0;
if (int.TryParse(configJOTypeValues[i], out IdValue))
jobOrderTypeId.Add(IdValue);
}
ViewBag.IsAutoSelectFileForJobOrder = false;
var vmCustomerDoc = new ViewModels.CustomerDocument();
var isDocSelected = false;
foreach (var doc in customerDocuments)
{
if (doc != null && jobOrderTypeId.Contains(myQuery.JobTypeId) && (doc.DocumentName.Contains("File1") || doc.DocumentName.Contains("File2")))
{
vmCustomerDoc.IsAutoSelectFile = true;
isDocSelected = vmPCustomerDoc.IsAutoSelectFile;
ViewBag.IsAutoSelectFileForJobOrder = isDocSelected;
}
else
{
vmCustomerDoc.IsAutoSelectFile = false;
ViewBag.IsAutoSelectFileForJobOrder = isDocSelected;
}
}
}
catch
{
//Leave it empty
}
return View();
}
ShowJobType.cshtml
@{
ViewBag.Title = "ViewJobType";
Layout = "~/Views/Shared/_Layout.cshtml";
}
var docs = ViewBag.CustomerDocuments as List<VM.CustomerDocument>; //Links to CustomerDocument.cs View Model
<table>
<tr>
<th>Check to Include in Email</th>
<th>Files</th>
</tr>
@foreach (var doc in docs)
{
<tr>
<td>
@{
var docValue = doc.DocumentId + (string.IsNullOrEmpty(doc.DocumentPath) ? "" : "/" + doc.DocumentPath);
}
<input type="checkbox" name="DocEmail" id="DocEmail" value="@docValue" @(ViewBag.IsAutoSelectGuideForJobOrder) ? "checked=\"checked\"" : "") />
</td>
</tr>
}
</table>
假設ViewBag.CustomerDocuments
具有已更新的視圖模型以設置其IsAutoSelectFile
屬性,則可以更改顯示檢查的邏輯,以檢查每個文檔上的該屬性值,並使用該邏輯將檢查添加到輸入字段。
<input type="checkbox" name="DocEmail" id="DocEmail" value="@docValue" @(doc.IsAutoSelectFile) ? "checked" : "") />
此外,在后端的當前邏輯中,將isDocSelected
設置為true后,它將始終為true。 如果使用ViewModel的屬性而不是view bag,則無論如何都可以從邏輯中刪除它的用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.