0
votes

Recently, I quite often get errors that work in dev but not in production, and this is the one. When submitting partial page using AJAX I've got error "500 Internal Server Error" . The detail that captured by Firebug:

Exception details

Controller: TimeKeeper
Action: Edit
Message: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'StateID'.
StackTrace:

Exception:    at System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name)
   at System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes)
   at System.Web.Mvc.Html.SelectExtensions.DropDownList(HtmlHelper htmlHelper, String name, IEnumerable`1 selectList, String optionLabel, Object htmlAttributes)
   at ASP._Page_Views_TimeKeeper__Edit_cshtml.Execute() in c:\inetpub\wwwroot\[appname]\Views\TimeKeeper\_Edit.cshtml:line 64
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)

_Edit.cshtml (Partial):

@model appname.ViewModels.TimeKeeperEditViewModel

<link href="@Url.Content("~/Content/datepicker.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/datepicker3.css")" rel="stylesheet" type="text/css" />

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Edit Time Keeper</h4>
</div>

@using (Ajax.BeginForm("Edit", "TimeKeeper",
    new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "POST",
        OnComplete = "editTimeKeeperComplete",
        UpdateTargetId = "timeKeeperList"
    }))
{
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.TimeKeeperID)
    @Html.HiddenFor(model => model.BillingID)

    <div class="modal-body">
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-md-4">
                    <label for="billingRate" class="control-label">Billing Rate</label>
                </div>
                <div class="col-md-8">
                    @Html.EditorFor(model => model.BillingRate, new { htmlAttributes = new { @class = "form-control" } })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-4">
                    <label for="billingStartDate" class="control-label">Billing Start Date</label>
                </div>
                <div class="col-md-8">
                    @Html.EditorFor(model => model.BillingStartDate, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-4">
                    <label for="status" class="control-label">Status</label>
                </div>
                <div class="col-md-8">
                    @Html.DropDownList("StateID", null, String.Empty, new { @class = "form-control" })
                </div>
            </div>
        </div>
    </div>

    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" id="btnClose">Close</button>
        <button type="submit" class="btn btn-primary" id="btnSave">Save changes</button>
    </div>
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#BillingStartDate").datepicker({
            format: "dd/mm/yyyy",
            todayBtn: "linked",
            autoclose: true,
            todayHighlight: true
        });
    });
</script>

This code to populate StateID:

private void PopulateStateDropDownList(object selectedState = null)
        {
            var statesQuery = from s in db.States
                              where s.RowStatus == true && s.StateGroupID == 1
                              orderby s.Name
                              select new
                              {
                                  StateID = s.StateID,
                                  Name = s.Name
                              };

            ViewBag.StateID = new SelectList(statesQuery, "StateID", "Name", selectedState);
        }

Post action code:

[HttpPost]
        public ActionResult Edit(TimeKeeperEditViewModel timeKeeperEditVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    LogHelper.logger.Info("Model Valid");
                    TimeKeeper timeKeeper = db.TimeKeepers.Find(timeKeeperEditVM.TimeKeeperID);
                    timeKeeper.BillingRate = timeKeeperEditVM.BillingRate;
                    timeKeeper.BillingStartDate = timeKeeperEditVM.BillingStartDate;
                    timeKeeper.BillingEndDate = timeKeeperEditVM.BillingEndDate;
                    timeKeeper.StateID = timeKeeperEditVM.StateID;

                    LogHelper.logger.Info("Save");
                    db.Entry(timeKeeper).State = EntityState.Modified;
                    db.SaveChanges();

                    LogHelper.logger.Info("Get Timekeepers");
                    Billing billing = db.Billings.Find(timeKeeperEditVM.BillingID);
                    BillingTimeKeeperViewModel billingVM = new BillingTimeKeeperViewModel()
                    {
                        BillingID = billing.BillingID,
                        TimeKeepers = billing.TimeKeepers
                    };

                    LogHelper.logger.Info("Return");
                    return PartialView("_List", billingVM.TimeKeepers);
                }
                else
                {
                    LogHelper.logger.Info("Model is not Valid");
                    return PartialView("_Edit");
                }
            }
            catch (Exception ex)
            {
                LogHelper.logger.Error(ex);
                return RedirectToAction("Index", "Error", ex);
            }
        }

I'm using NLog to see the problem. There is no error, but the ModelState.IsValid is false

UPDATE

I placed log before if (ModelState.IsValid) to print out BillingRate, BillingStartDate, BillingEndDate, and StateID. It's caused by BillingEndDate is null if I fill day more than 12 for example 13/1/2014, but If I fill with 12/1/2014 the ModelState.IsValid is true.

So my conclusion, it caused by date format. The problem is I prohibited to change server date format. Any suggestion?

1
How you're populating "StateID" dropdownlist? Is your controller expecting 'IEnumerable<SelectListItem>' type parameter?malkam
@malkam I updated my question to show you how to populate "StateID" dropdownlistWilly
@EhsanSajjad I updated the questionWilly

1 Answers

0
votes

It is generally bad to pass drop down lists through the viewbag. I would recommend putting that into the model

public List<SelectListItem> StateList { get; set; }

then populate this list with your database call

foreach(var temp in statesQuery){
    model.StateList.Add(new SelectListItem() { Text = temp.Name, Value = temp.StateID });
}

then on your view change your drop down list to

@Html.DropDownListFor(x => x.StateID, Model.StateList)

you can set the drop down on the controller by setting model.StateID and the selected value from the drop down will be tied to that field on post back