模型值无法访问

时间:2014-01-18 20:52:22

标签: asp.net-mvc

我有一个模型,其中包含有关帐户的一些详细信息(名称,ID等),然后它有一个名为Transaction的类型,其中包含有关当前所选帐户事务的信息。然后,事务可以具有许多事务线。所以我有一个List<TransactionsLine>属性。

我正在尝试使用模型设置下拉列表的值,该值位于List&lt;&gt;中属性。目前,可以而且必须只有列表中的一个项目。

@Html.DropDownListFor(x=>x.Transaction.TransactionLines[0].CategoryId, Model.TransactionReferences.Categories, new {@onchange="populateSubCategory()"})

但是,当我运行它时,列表默认为列表中的第一项。

在调试模式下,当我将鼠标悬停在x.Transaction.TransactionLines[0].CategoryId上时,它不会显示值。但是当鼠标悬停在集合Model.TransactionReferences.Categories上时,我看到它有一个有效的列表。它只是不会设置所选的值。

我这样做错了吗?

它适用于我使用的其他下拉菜单,但选择值是我模型的最高级别:

 @Html.DropDownListFor(x => x.Transaction.ThirdPartyId, Model.TransactionReferences.ThirdParties, new { @class = "cmbThirdParty form-control", @onchange = "populateDefaults()" })

那个工作正常。

注意,手动执行,有效:

<select class="form-control" id="cmbCategory" onchange="populateSubCategory()">
                        <option value="0">Select a One</option>
                        @foreach (var cat in Model.TransactionReferences.Categories)
                        {
                            //var selected = cat.Value == Model.Transaction.TransactionLines[0].CategoryId.ToString() ? "selected" : "";
                            <option value="@cat.Value">@cat.Text</option>   
                        }
                    </select>

但感觉不是最好的方法。

型号:

传递给视图的主要模型:

public class TransactionModel
    {
        public int BankAccountId { get; set; }
        public string BankAccountName { get; set; }

        public TransactionContainer Transaction { get; set; }
        public TransactionReferenceModel TransactionReferences { get; set; }

        public DateTime DefaultDate { get; set; }

    }

TransactionReferenceModel保存用于填充下拉列表的所有“引用”数据:

public class TransactionReferenceModel
{
    public List<SelectListItem> TransactionTypes { get; set; }
    public List<SelectListItem> EntryTypes { get; set; }
    public List<SelectListItem> SubCategories { get; set; }
    public List<SelectListItem> Categories { get; set; }
    public List<SelectListItem> ThirdParties { get; set; }
    public List<SelectListItem> CostCentres { get; set; }
}

TransactionContainer模型包含有关所选交易的所有主要详细信息:

public class TransactionContainer
    {
        public int Id { get; set; }
        public int AccountId { get; set; }

        public int TransactionTypeId { get; set; }
        public string TransactionType { get; set; }

        public int EntryTypeId { get; set; }
        public string EntryType { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/dd/yyyy}")]
        public DateTime TransactionDate { get; set; }

        public string ThirdParty { get; set; }
        public int ThirdPartyId { get; set; }

        public string Account { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
        public decimal Amount { get; set; }

        public string Notes { get; set; }

        public string CategoryDisplay { get; set; }
        public string CostCentreDisplay { get; set; }

        public decimal RunningBalance { get; set; }

        public List<TransactionLine> TransactionLines { get; set; }

    }

然后保存构成交易的交易行列表。事务行保存我尝试将下拉列表设置为的属性,即CategoryId:

public class TransactionLine
{

    public int Id { get; set; }
    public int TransactionId { get; set; }

    public int? CostCentreId { get; set; }
    public string CostCentre { get; set; }

    public int SubCategoryId { get; set; }
    public string SubCategory { get; set; }

    public int CategoryId { get; set; }
    public string Category { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
    public decimal Amount { get; set; }

    public string Notes { get; set; }

}

以下是我填充模型并将其发送到视图的方式:

public ActionResult EditTransaction(int? transactionId, int? bankAccountId)
        {

            // Create the main view object
            var model = new TransactionModel
                {
                    Transaction = new TransactionContainer
                        {
                            TransactionLines = new List<TransactionLine>()
                        }
                };



            if (transactionId != null) // This is an Edit, as opposed to an Add
            {
                var item = new TransactionService(currentUserId).GetTransaction(transactionId.Value);

                // Populate the Reference object used to populate drop downs.
                model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, item.TransactionLines[0].SubCategoryId);

                model.BankAccountId = item.AccountId;
                model.BankAccountName = item.Account.FullName;
                model.DefaultDate = Session["DefaultDate"] != null
                                      ? DateTime.Parse(Session["DefaultDate"].ToString())
                                      : DateTime.UtcNow;

                model.Transaction.AccountId = item.AccountId;
                model.Transaction.Amount = item.Amount;
                model.Transaction.TransactionLines.Add(new TransactionLine
                    {
                        Id = item.TransactionLines[0].Id,
                        CategoryId = item.TransactionLines[0].SubCategory.CategoryId,
                        CostCentreId = item.TransactionLines[0].CostCentreId,
                        Notes = item.TransactionLines[0].Notes,
                        Amount = item.TransactionLines[0].Amount,
                        SubCategoryId = item.TransactionLines[0].SubCategoryId,
                        TransactionId = model.Transaction.Id

                    });
                model.Transaction.EntryTypeId = item.EntryTypeId;
                model.Transaction.Id = transactionId.Value;
                model.Transaction.Notes = item.Notes;
                model.Transaction.ThirdPartyId = item.ThirdPartyId;
                model.Transaction.TransactionDate = item.TransactionDate;
                model.Transaction.TransactionTypeId = item.TransactionTypeId;
            }
            else
            {
                // Populate the bank account details
                var bank = new BankAccountService(currentUserId).GetBankAccountById(bankAccountId.Value);
                model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, null);

                model.BankAccountId = bank.Id;
                model.BankAccountName = bank.FullName;
                model.Transaction.TransactionLines.Add(new TransactionLine
                    {
                        TransactionId = model.Transaction.Id // Link the transaction line to the transaction.

                    });

                var transactionDate = Session["DefaultDate"] != null
                                          ? DateTime.Parse(Session["DefaultDate"].ToString())
                                          : DateTime.UtcNow;

                // Populate the object to hold the Transaction data, so that we can use it and return it in the view.
                model.Transaction.TransactionDate = transactionDate;

            }


            return View(model);


        }

1 个答案:

答案 0 :(得分:1)

我认为您应该在视图中使用SelectList构造函数,以指示默认值,如下所示:

@Html.DropDownListFor(
    x => x.Transaction.TransactionsLines[0].CategoryId, 
    new SelectList(Model.TransactionReferences.Categories, "Value", "Text", Model.Transaction.TransactionsLines[0].CategoryId)
)

您不限于使用 List&lt;集合的SelectListItem&gt; 。您也可以使用特定类的列表。

这是Controller Action Method代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var m = new AccountModel();
        m.Transaction = new Transaction();
        m.Transaction.TransactionsLines = new List<TransactionsLine>();
        m.Transaction.TransactionsLines.Add(new TransactionsLine() { CategoryId = 2 });
        m.TransactionReferences = new TransactionReferences();
        m.TransactionReferences.Categories = new List<SelectListItem>()
        {   new SelectListItem() { Text = "Cat1", Value = "1" },
            new SelectListItem() { Text = "Cat2", Value = "2" },
            new SelectListItem() { Text = "Cat3", Value = "3" }
        };
        return View(m);
    }
}