Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I think the issue is in the create action, posting some code, NO ERRORS, just empty database fields for Categories, Priorities and Site_Admins fields on my tickets table, I am trying to create a page that will save to database, and then pull up a list of database items, When I click the create button on the create page, the list page shows up, Everything except those fields listed above are populated in the database or on the view page.
CONTROLLER:

C#
public class TicketsController : Controller
    {
        // GET: Tickets
        
        Helpdesk2017Db _db = new Helpdesk2017Db();
     
        // GET: Tickets
        public ActionResult Tickets()
        {
            var model = from a in _db.Tickets orderby a.Date ascending select a;
            
            return View(model);
        }

        // GET: Tickets/Details/5
        public ActionResult Details(int id)
        {
            var view = _db.Tickets.Single(v => v.Id == id);
            return View(view);
        }

        // GET: Tickets/Create
        public ActionResult Create()
        {   
            ViewData["Categories"] = new SelectList(_db.Categories, "Id", "CategoryName");     
            ViewData["Priorities"] = new SelectList(_db.Priorities, "Id", "PriorityName");     
            ViewData["Site_Admins"] = new SelectList(_db.Site_Admins, "Id", "Name");
            return View("Create");
        }

        // POST: Tickets/Create
        [HttpPost]
        public ActionResult Create(Tickets Tickets)
        {
            if (ModelState.IsValid)
            {
                _db.Tickets.Add(Tickets);
                _db.SaveChanges();
                // TODO: Add insert logic here
                return RedirectToAction("Tickets");
            }
            return View("Tickets");
        }

MODEL:
C#
public class Tickets
    {
        public IEnumerable<selectlistitem> Priorities { get; set; }
        public IEnumerable<selectlistitem> Categories { get; set; }
        public IEnumerable<selectlistitem> Site_Admins { get; set; }
        public int Id { get; set; }
        public DateTime Date { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public long Telephone { get; set; }
        public string Location { get; set; }
        public string Region { get; set; }
        public string ComputerName { get; set; }
        public long AssetTag { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
      //public  File
      //public  File  
      //public File     
    }
}

CREATE VIEW:
HTML
@Html.DropDownList("Id", ViewData["Site_Admins"] as SelectList, "Assign To", new { @class = "form-control", @id = "Id" })
            @Html.DropDownList("Id", ViewData["Priorities"] as SelectList, "Select Priority", new { @class = "form-control", @id = "Id" })
            @Html.DropDownList("Id", ViewData["Categories"] as SelectList, "Select Category", new { @class = "form-control", @id = "Id" })


The list view is well just a basic list pulling from database,
I know everything worked before I added the dropdown list info. The dropdowns work correctly, the issue is saving selected item from create page, to add to database, along with other text on the page, and pull to list view as a listed "Ticket"

What I have tried:

I have tried every version of dropdownlist and dropdownlistfor code on the internet I could find, for the controller, the class and the view

I am almost positive the problem is in the controller code that I listed first.

I am using SQL 2016 express database.
Posted
Updated 6-Apr-17 10:31am
v10
Comments
Timothy Heckler 1-Apr-17 10:39am    
Thank you Bryian Tan for fixing my post.
Graeme_Grant 1-Apr-17 10:41am    
That's the view and controller. You difficulty is with the DB and that code is missing + any errors encountered.

Developers sacrifice and contribute their own time for free to help fellow developers resolve difficulties. It is important that you are crystal clear about what you are experiencing with plenty of information so that your time and theirs are not wasted. The clearer the question, the better chance that you will get a favorable response in a timely manner.

Please take the time to look at these links provided before posting questions:
* Basic Debugging with Visual Studio 2010 - YouTube[^]
* Some guidelines for posting questions in the forums[^]
* Tales from the Evil Empire - Asking questions is a skill[^]

Once you are ready update the question with clear and concise details, sample code, any error messages (including inner exception details), etc, please click on Improve question to add more info to the question.
Graeme_Grant 1-Apr-17 10:54am    
That is the table creation, where is the add to table that has the error and the error message??

Again, please click on Improve question to add more info to the question.
Graeme_Grant 1-Apr-17 11:08am    
The SQL code that you shared is used to create a table, not save data to a table. Your last question is about loading/reading data from a table and displaying in a list. 3 totally different things. Do you know what you want to do as the questions asked do not relate?

Here are some getting start articles:
* SQL: Get Started Learning SQL[^]
* MVC + DB: ASP.NET MVC Working with Data | The ASP.NET Site[^]
Graeme_Grant 1-Apr-17 11:24am    
I don't know any other way of putting it but so far you have failed to produce any code that relates to your question above. I've already spent too much time on this. Maybe someone else will answer.

Start by fixing your model to match your database:
C#
public class Tickets
{
    public string Priorities { get; set; }
    public string Categories { get; set; }
    public string Site_Admins { get; set; }
    ...

NB: There's no need for the database columns to be nvarchar(max) - you're only going to be storing a single value in each field. If you want multiple values in each field, then your database structure is wrong, and you can't use a drop-down list. :)

You'll need to re-populate the lists in the ViewData if the posted model is not valid, so it's probably worth pulling that out into another method:
C#
private void PopulateLists(Tickets model)
{
    // NB: Using the "model" parameter to preserve the selected value when the user submits the form:
    ViewData["Categories"] = new SelectList(_db.Categories, "Id", "CategoryName", model.Categories);     
    ViewData["Priorities"] = new SelectList(_db.Priorities, "Id", "PriorityName", model.Priorities);
    ViewData["Site_Admins"] = new SelectList(_db.Site_Admins, "Id", "Name", model.Site_Admins);
}

public ActionResult Create()
{
    var model = new Tickets();
    PopulateLists(model);
    return View(model);
}

public ActionResult Create(Tickets model)
{
    if (!ModelState.IsValid)
    {
        PopulateLists(model);
        return View(model);
    }
    
    _db.Tickets.Add(model);
    _db.SaveChanges();
    return RedirectToAction("Tickets");
}

NB: I just noticed the SaveChangesAsync call. You either need to use the synchronous SaveChanges method, or make your action async and await the results:
C#
public async Task<ActionResult> Create(Tickets model)
{
    if (!ModelState.IsValid)
    {
        PopulateLists(model);
        return View(model);
    }
    
    _db.Tickets.Add(model);
    await _db.SaveChangesAsync();
    return RedirectToAction("Tickets");
}


In your view, make sure you have the correct class specified in the @model directive, and then use the DropDownListFor helper:
@Html.DropDownListFor(m => m.Site_Admins, (SelectList)ViewState["Site_Admins"], "Assign To", new { @class = "form-control" })
@Html.DropDownListFor(m => m.Priorities, (SelectList)ViewData["Priorities"], "Select Priority", new { @class = "form-control" })
@Html.DropDownListFor(m => m.Categories, (SelectList)ViewData["Categories"], "Select Category", new { @class = "form-control" })

This will generate three <select> elements with the correct name and ID, which will allow the model binder to match the posted value to the property on the model.
 
Share this answer
 
v2
Comments
Timothy Heckler 6-Apr-17 13:07pm    
The thing about "fixing the model to match the database" each one of those drop down lists have their own model, and views and controllers, reason being is I need those dropdown lists to be able to create, edit or delete to their own tables. That is why I had it set up that way. Everything works the way I have it set up, just trying to figure out the code to make selected Item populate in tickets database, everything in the form except the dropdownlist info is saving just fine. as far as "savechangesAsync();" I forgot to update that when I resubmitted this question, I had already made that change, apologize.
Richard Deeming 6-Apr-17 13:12pm    
Yes, the entities you're linking to will have their own models/views/controllers.

But when you're editing a Tickets, you are selecting the primary key of a single entity to associate with your new Tickets instance.

That posts a single value to the server - eg: Site_Admins=42 - and the model binder has no way to map that to a collection of Site_Admins entities.

And even if it did, Entity Framework would have no way to map a collection of Site_Admins entities back to the ID of the single entity you want to associate with the new Tickets entity.
Timothy Heckler 6-Apr-17 16:21pm    
Ok, See solution 3, Now the only issue I have is the database is only recording the ID of the dropdowns, instead of the name, should I create fields in the table for the CategoryName, PriorityName, and Name(for Site_Admins) ?
Richard Deeming 7-Apr-17 6:31am    
That's what it's supposed to do. You store the primary key of the lookup record on the ticket, and join to the lookup table if you need to retrieve the name.

It's basic database normalization.
Timothy Heckler 7-Apr-17 8:20am    
I understand that, However what I wanted to do, was put the name of the selected item in both the database and the dropdownlist, So what I ended up doing was just calling the selected item name twice and omitted the Id all together, it may not be right, it may be dirty, but it works for my purposes, thank you for your help.
I was able to take a mixture of my original code and Richard Deeming's suggested code to make this work, however the dropdown lists show the correct way, but in the database it only saves the ID, I do not want it to save the ID, I want it to save the "name" selected from dropdown list to database. Any Ideas what to add or change?

Changes to code, I took his suggestion on pulling out the [viewdata] code and placed it in a public void,

then left my create code alone except for adding PopulateList(model) as he suggested.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900