0

Hello friends this really basic question in mvc, but iam lot of search i couldn't find it.

Control:

if (objResponse.ErrorNo == 0)
 {
     lstReason.Add(new SelectListItem { Value = "1", Text = "Select" });
     foreach (XElement xEle in resXml.Descendants("R"))
             {
               lstReason.Add(new SelectListItem { Value = xEle.Element("C1").Value, Text = xEle.Element("C2").Value });
              }
               ViewBag.ReasonCode = lstReason;

                }
   }

View:

@Html.DropDownListFor(m => m.ReasonCode, new SelectList(ViewBag.ReasonCode, "Value", "Text"), new { @class = "form-control autofocus", @id = "ddlReason" })

I got it only m => m.ReasonCode but how can get m.reason from ViewBag.ReasonCode text value.

Any help would be really appreciated.

Prabhat Sinha
  • 1,500
  • 20
  • 32
  • Possible duplicate of [Can the ViewBag name be the same as the Model property name in a DropDownList?](https://stackoverflow.com/questions/37161202/can-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist) –  May 22 '17 at 21:59
  • As a side note, creating an identical `IEnumerable` from the original one using `new SelectList(..)` in the view is pointless extra overhead. –  May 22 '17 at 22:02
  • And the normal way to add the option label is using [this overload](https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor(v=vs.118).aspx#M:System.Web.Mvc.Html.SelectExtensions.DropDownListFor``2(System.Web.Mvc.HtmlHelper{``0},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.Collections.Generic.IEnumerable{System.Web.Mvc.SelectListItem},System.String,System.Object) which add a `null` value for validation –  May 22 '17 at 22:03

1 Answers1

1

Your ViewBag member cannot be named the same as your model property. The "selected" value is determined from ModelState, which is composed of values from Request, ViewData/ViewBag and finally Model. As a result, you're essentially saying the that "selected" value should be the entire list of SelectListItems, which obviously does not match an item in that list. Change your ViewBag member to something like ViewBag.ReasonCodeOptions, and you'll be good.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • ok am change my viewbag name but how can catch value of drop-down text name value @Html.HiddenFor(m => m.ReasonCode) @Html.HiddenFor(m => m.ReasonText) – Prabhat Sinha May 23 '17 at 04:27