0

Hello in my app I have a dropdown list

in my controller I use this

public ActionResult Create()
    {

        webdata db = new webdata();
        ViewBag.annCategories = new SelectList(db.annCategories, "kind", "an_kindtext");
        return View();

    }

EDIT in my HttpPost I have

    [HttpPost]
    [ValidateAntiForgeryToken]

    public ActionResult Create([Bind(Include = "ann_ID,Pubdate,kind,title")] announcements announcements)
    {
        if (ModelState.IsValid)
        {
            db.announcements.Add(announcements);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(announcements);
    }

and in my view I have this

@Html.DropDownList("annCategories",null, new { id = "annCategories" })

I see the values in my dropdown list, when I click the create button a new record is stored in the database. But it always saves the "Select a category" which is the first option. Can someone help with this? thank you

EDIT

My announcement model

public class announcements
{
    [Key]
    [Display(Name = "ID")]
    public int ann_ID { get; set; }


    [Display(Name = "Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Pubdate { get; set; }

    [Display(Name = "Category")]
    public int kind { get; set; }


    [Display(Name = "title")]
    public String title { get; set; }

    }

My announcement categories model

public class annCategories
{

    [Key]
    [Display(Name = "Category")]
    public int kind { get; set; }


    [Display(Name = "Description")]
    public String an_kindtext { get; set; }

}

tereško
  • 58,060
  • 25
  • 98
  • 150
touinta
  • 971
  • 3
  • 10
  • 26
  • Is there a Database record with the 'Select a category' saved on the category table? if so id imagine this is pretty valid as the DropDown value would be the Id of the 'Select a category' option if a category isn't being selected – Ian Mar 07 '16 at 16:04
  • Yes there is a record with the "Select a category" but is saved to all records whatever I choose – touinta Mar 07 '16 at 18:35

1 Answers1

1

It is not saving "Select a category". It is saving the default values of you model because you never bind anything to property kind so when you submit the form the value of kind is 0.

Start by creating a view model to represent what you want to display in the view

public class AnouncementVM
{
    public int? ID{ get; set; }
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}"] // see notes below
    public DateTime Date { get; set; }
    public int Category { get; set; }
    public string Title{ get; set; }
    public IEnumerable<SelectListItem> CategoryList { get; set; }
}

Note the [DataType(DataType.Date)] adds the type="date" attribute in order to render the browsers datepicker (which is only implemented in Chrome and Edge) so unless your using that, then it can be removed, but if you are using it, then you must also use [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] (i.e. the format must be yyyy-MM-dd)

Then in the GET method

public ActionResult Create()
{
    var model = new AnouncementVM
    {
        CategoryList = new SelectList(db.annCategories, "kind", "an_kindtext")
    };
    return View(model)
}

and in the view

@Html.DropDownListFor(m => m.Category, Model.CategoryList, "Please select")

and in the POST method

[HttpPost]
public ActionResult Create(AnouncementVM model)
{
    if (!ModelState.IsValid)
    {
        model.CategoryList = new SelectList(db.annCategories, "kind", "an_kindtext");
        return View(model);
    }
    announcements data = new announcements
    {
        Pubdate = model.Date,
        kind = model.Category,
        title = model.Title
    };
    db.announcements.Add(data);
    db.SaveChanges();
    return RedirectToAction("Index");
}
Community
  • 1
  • 1
  • thank you for your reply, I am getting the error: Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) I search it but I didn't find a solution. The error appears at the controller at line: CategoryList = new SelectList(db.annCategories, "kind", "an_kindtext") – touinta Mar 08 '16 at 07:21
  • That's because you have the wrong `using` statements. It needs to be `System.Web.Mvc.SelectList` (and if you need both those using statement in you assembly, then you need to use the fully qualified assembly name). –  Mar 08 '16 at 07:24
  • I add it but it sais: A using namespace directive can only be applied to namespaces; 'System.Web.Mvc.SelectList' is a type not a namespace – touinta Mar 08 '16 at 07:30
  • I have no idea what you have done, or why you would have `using System.Web.WebPages.Html` in your model - it should be deleted, but if it cannot, then you need to use `public IEnumerable CategoryList { get; set; }` –  Mar 08 '16 at 07:33
  • ok I correct it. Now if i add your code to my HttpPsot I get varius errors. Can you see my EDIT in my question. thank you very much – touinta Mar 08 '16 at 07:52
  • You stated you were using a **view model** - your not - you using the data model which is awful practice and no wonder your getting errors. But I can't guess what the errors are –  Mar 08 '16 at 07:54
  • sorry you are right. The error is 'Myproject.Models.announcements' is a 'type' but is used like a 'variable'. Sorry for not being clear. – touinta Mar 08 '16 at 07:57
  • Why the use of data model is not a good practice is there any other way to get my data from my table? thank you – touinta Mar 08 '16 at 07:59
  • Create a view model (say) `AnnouncementVM` and copy the properties from your data model to the view model plus the `SelectList` property (that cannot be in your data model). Then use `@AnouncementVM` in the view and change the POST method to `public ActionResult Create(AnouncementVM model)` and in the method initialize a new instance of your announcements data model, set its property values based on the view model and save the data model. –  Mar 08 '16 at 07:59
  • And I suggest you read [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Mar 08 '16 at 08:00
  • I guess I understood the diffrence but can you help me with "...and in the method initialize a new instance of your announcements data model, set its property values based on the view model and save the data model." – touinta Mar 08 '16 at 12:21
  • @touinta, Its late and I need some sleep, but in the morning I will update the answer showing all steps in using a view model (including how to save the data) - I would have done it initially except that you said you were using a view model :). I also strongly recommend you follow normal naming conventions for your models and its properties, at least in the view models. –  Mar 08 '16 at 12:24
  • ok thank you. Well some of them are coming from Greeks which is my language :). I will try to correct them. have a goodnight! – touinta Mar 08 '16 at 12:36
  • It was more things like `announcements` should be `Anouncement` and `annCategories` should be `AnouncementCategory` (each class describes one object - i.e. not plural) and things like `an_kindtext` which should be `Desciption` or `KindText` - not sure what kind means here :) –  Mar 08 '16 at 12:40
  • Yes you are right. and the kindtext is the Decription of the kind of the announcement. :) anyway have a goodnight! Here is still afternoon so I will keep reading... – touinta Mar 08 '16 at 13:01
  • hello, thank you for the details. I actually used my code I just change the @Html.DropDownList("annCategories",null, new { id = "annCategories" }) to @Html.DropDownList("kind",null, new { id = "annCategories" }). I did the same in the view bag at my controller and it worked. I didn't want to bother you more. thank you again – touinta Mar 09 '16 at 15:47