ASP.NET MVC - 未将对象引用设置为DropDownList中的对象实例

时间:2017-11-18 15:38:07

标签: asp.net-mvc-4

我有一个模型类

public partial class FEES
{
    public FEES()
    {

    }
    public long FEE_ID { get; set; }

    public decimal AMOUNT { get; set; }

    public int CURRENCY_ID { get; set; }

    public string NAME { get; set; }

    public virtual CURRENCIES CURRENCIES { get; set; }
}

视图模型

public class FeesViewModel
{
    public SelectList CurrenciesList { get; set; }
    public FeesViewModelInput input { get; set; }

    public class FeesViewModelInput
    {
        [HiddenInput]
        public long FEE_ID { get; set; }

        [Display(Name = "Amount")]
        [Required(ErrorMessage = "Fee Amount Is Required!")]
        [RegularExpression(@"^[0-9,.]+$", ErrorMessage = "Please enter proper currency format e.g. 2,500")]
        public decimal AMOUNT { get; set; }


        [Display(Name = "Currency")]
        [Required(ErrorMessage = "Currency Is Required!")]
        public int CURRENCY_ID { get; set; }

        [Required(ErrorMessage = "Fee Name Is Required!")]
        [Display(Name = "Fee Name")]
        public string NAME { get; set; }
    }
}

ViewModel的小型服务

    public void createFees(FEES fee, FeesViewModel viewModel)
    {
        fee.FEE_ID = viewModel.input.FEE_ID;
        fee.CURRENCY_ID = viewModel.input.CURRENCY_ID;
        fee.NAME = viewModel.input.NAME.Trim();
    }

我在控制器中调用服务和ViewModel。

控制器

    public ActionResult Create()
    {
        FeesViewModel fees = new FeesViewModel();
        fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
        fees.FeeTypesList = new SelectList(_feetypesService.GetFeeTypes().Where(c => c.ACTION_STATUS != 2), "FEE_TYPE_ID", "FEE_TYPE_NAME");
        return View();
    }


    [HttpPost]
    public ActionResult Create(FeesViewModel fees)
    {
        try
        {
            if (ModelState.IsValid)
            {
                //check if values is duplicate
                if (_feesService.GetFees().Where(c => c.ACTION_STATUS != 2).Any(c => c.NAME.ToLower().Trim() == fees.input.NAME.ToLower().Trim()))
                {
                    this.AddNotification("Fee Name already exist.<br/> Kindly verify the data.", NotificationType.ERROR);
                }
                else
                {
                    var fee = new BPP.CCSP.Admin.Web.BPPCCSPAdminFeesService.FEES();
                    var helper = new FeesService();
                    helper.createFees(fee, fees);
                    _feesService.AddFee(fee);
                    var notif = new UINotificationViewModel()
                    {
                        notif_message = "Record saved successfully",
                        notif_type = NotificationType.SUCCESS,
                    };
                    TempData["notif"] = notif;
                    return RedirectToAction("Index");

                }
            }
        }
        catch (Exception e)
        {
            this.AddNotification("Fees cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
        }
        fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
        return View(fees);
    }

和视图

@model BPP.CCSP.Admin.Web.ViewModels.FeesViewModel

@{
//ViewBag.Title = "Create";
}
<div class=" box box-body box-primary">

    @using (Html.BeginForm("Create", "Fees", FormMethod.Post, new { @class = "form-horizontal", @enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    @Html.ValidationSummary(true, null, new { @class = "text-danger" })
    @*@Html.HiddenFor(model => model.faculty_activation_date, new { @Value = System.DateTime.Now })*@
    <div class="row .col">
        <div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
            <div class="panel panel-info">
                <div class="panel-heading">
                    <div class="panel-title">Create Fee</div>
                </div>
                <div class="panel-body">

                    <div class="col-md-6">
                        <div>
                            @Html.LabelFor(model => model.input.NAME, "Fee Name")
                            @Html.TextBoxFor(model => model.input.NAME, new { @style = "border-radius:3px;", @type = "text", @class = "form-control", @placeholder = Html.DisplayNameFor(m => m.input.NAME), @autocomplete = "on" })
                            @Html.ValidationMessageFor(model => model.input.NAME, null, new { @class = "text-danger" })
                        </div>
                        <div>
                            @Html.LabelFor(model => model.input.AMOUNT, "Amount")
                            @Html.TextBoxFor(model => model.input.AMOUNT, new { @style = "border-radius:3px;", @type = "text", @class = "form-control", @placeholder = Html.DisplayNameFor(m => m.input.AMOUNT), @autocomplete = "on" })
                            @Html.ValidationMessageFor(model => model.input.AMOUNT, null, new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div>
                            @Html.LabelFor(model => model.input.CURRENCY_ID, "Currency")
                            @*@Html.DropDownList("CURRENCY_ID", (IEnumerable<SelectListItem>)ViewBag.name, "Please Select a Currency", new { @class = "form-control", @style = "border-radius:3px;" })*@
                            @Html.DropDownListFor(x => x.input.CURRENCY_ID, Model.CurrenciesList, "Please Select a Currency", new { @class = "form-control", @style = "border-radius:3px;" })
                            @Html.ValidationMessageFor(model => model.input.CURRENCY_ID, null, new { @class = "text-danger" })
                        </div>
                        <div>
                            @Html.LabelFor(model => model.input.FEE_TYPE_ID, "Fee Type")
                            @Html.DropDownListFor(model => model.input.FEE_TYPE_ID, Model.FeeTypesList, "Please Select a Fee Type", new { @class = "form-control", @style = "border-radius:3px;" })
                            @Html.ValidationMessageFor(model => model.input.FEE_TYPE_ID, null, new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                    <div class="panel-footer">
                        <div class="panel-title">
                            <div class="form-actions no-color">
                                <input type="submit" value="Create" class="btn btn-success" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</div>
}

</div>
}

当我点击查看(创建)时,我收到此错误

enter image description here

CurrencyID是来自CURRENCIES模型类的DropDownList。 我有这些问题:

  1. 为什么我收到此错误以及如何解决此问题。
  2. 如何在没有映射的情况下执行ViewModel。?

1 个答案:

答案 0 :(得分:0)

  
      
  1. 为什么我收到此错误以及如何解决此问题。
  2.   

因为您的视图中未设置Model。它是空的。

当用户访问Create页面时,您需要确保在下拉列表中显示选项。因此,您需要确保在GET期间将模型传递到视图中。

public ActionResult Create()
{
    // your code and pass fees to your view.
    return View(fees);
}
  
      
  1. 如何在没有映射的情况下执行ViewModel。任何一个例子。
  2.   

您可以使用AutoMapper NuGet包进行映射。