-1

I have simple site

controller.cs

public ActionResult Dodaj()
    {

        EduSiatkiEntities daneProgramu = new EduSiatkiEntities();

        SelectList profileHasel = new SelectList(daneProgramu.SYS_PROFILE_HASEL.Select(e => new{ Value = e.idProfiluHasla, Text = e.nazwaProfilu,}), "Value", "Text");
        ViewBag.profileHasel = profileHasel;
        ViewBag.CzyZapisanoDane = "nie";

        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Dodaj(Models.UzytkowniDodajkViewModel uzytkownikForm)
    {
        Debug.WriteLine(uzytkownikForm.idProfilHasla.Where(x => x.Selected=true).FirstOrDefault().Value.ToString());
        if (ModelState.IsValid)
        {
            /**/
        }
        else
        {
            ViewBag.CzyZapisanoDane = "nie";
        }

        return View(uzytkownikForm);
    }

view.cshtml

@Html.DropDownListFor(a => a.idProfilHasla, (SelectList)@ViewBag.profileHasel, "Wybierz opcje...", new { @class = "form-control" })

model.cs

[Display(Name = "Profil hasła użytkownika")]
    [Required(ErrorMessage = "Wybierz profil hasła użytkownika")]
    public IEnumerable<SelectListItem> idProfilHasla { get; set; }

When i debug the program I alway get NULL value from DropDownList (from code below)

Debug.WriteLine(uzytkownikForm.idProfilHasla.Where(x => x.Selected=true).FirstOrDefault().Value.ToString());
McStar
  • 1
  • 1
  • 1
  • 1
    Please post the relevant code for this - `Models.UzytkowniDodajkViewModel` – Judge Bread Mar 19 '17 at 18:18
  • Ok. First, "edit" your question and paste the class in the question and not as an answer. Secondly, you seem to be binding a drop down list selected _item_ to an IEnumerable which makes little sense. Change your IEnumerable to string and try with that. – Judge Bread Mar 19 '17 at 19:37
  • A ` –  Mar 19 '17 at 21:39

1 Answers1

0
@Html.DropDownListFor(a => a.idProfilHasla, (SelectList)@ViewBag.profileHasel, 
     "Wybierz opcje...", new { @class = "form-control" })

For above DropDownList , idProfilHasla should be string type, because DropDownList selected value is a string.

[Display(Name = "Profil hasła użytkownika")]
[Required(ErrorMessage = "Wybierz profil hasła użytkownika")]
public string idProfilHasla { get; set; }

If you want to place SelectList inside model instead of ViewBag, you might want to read this answer.

Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181
  • When I do this (code above) - I get error: **System.InvalidOperationException** :key idProfilHasla1, is type System.String, but must be IEnumerable – McStar Mar 25 '17 at 13:39