1

I'm trying to use the user selected item from the DropDownList to create a new entry in my Database table that is related/linked?(Not sure of correct wording for this) to the DropDownList item.
Here are my Models

public class TaskInstance
{
    public int Id { get; set; }
    public DateTime DueDate { get; set; }
    public int HowMany { get; set; }
    public Task TaskId { get; set; }

    public virtual Task Task { get; set; }
}
public class TaskInstanceViewModel
{
    [DataType(DataType.DateTime)]
    public DateTime DueDate { get; set; }
    public int HowMany { get; set; }
    public IEnumerable<SelectListItem> TaskList { get; set; }

    public virtual ICollection<Task> Task { get; set; }
}
public class Task
{
    public Task()
    {
        TaskInstance = new HashSet<TaskInstance>();
    }
    public int Id { get; set;}
    public string Name { get; set; }
    public string Unit { get; set; }

    public virtual ICollection<TaskInstance> TaskInstance { get; set; }
}

Controllers

public ActionResult Create()
    {
        var model = new TaskInstanceViewModel();
        model.TaskList = db.Task.ToList().Select(x => new SelectListItem
        {
            Value = x.Id.ToString(),
            Text = x.Name
        }).ToList();

        return View(model);
    }
    // POST: TaskInstances/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(TaskInstanceViewModel model)
    {
        if (ModelState.IsValid)
        {
            var taskinstance = new TaskInstance { DueDate = model.DueDate };
            db.TaskInstance.Add(taskinstance);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }

View - This is the only one I need to show I think, the others are just fields

@Html.DropDownListFor(x => Model.TaskList, (SelectList)Model.Task)

On the controller where it says var taskinstance = new TaskInstance { DueDate = model.DueDate }; Would be where i need to use the selected item from the User but I have no idea how to get it, i've looked through a lot of posts but most of them is just how to make the DropDownList in the first place but not how to use it(Being a link to another table) with a new database entry.

I'd also like to mention that I am still new to MVC so feel free to point out if im going about this the wrong way

2
  • have you tried model.Task? var task = model.Task Commented Dec 27, 2015 at 3:47
  • how can Model.Task be cast to a SelectList? Commented Dec 27, 2015 at 3:50

2 Answers 2

2

Add a new property of type int to store the selected task from the dropdown. Remember view models are specific to the view.so keep only those properties you absolutely need in the view, in your view model.

public class TaskInstanceViewModel
{       
    public DateTime DueDate { get; set; }
    public int HowMany { get; set; }
    public IEnumerable<SelectListItem> TaskList { get; set; }
    public int SelectedTask {set;get;} // new property
}

And in your view

@model TaskInstanceViewModel
@using(Html.BeginForm())
{
  <label> How many</label>
  @Html.TextBoxFor(s=>s.HowMany)
  <label>Due date</label>
  @Html.TextBoxFor(s=>s.DueDate)
  <label>Task</label>
   @Html.DropDownListFor(s => s.SelectedTask, Model.TaskList)

  <input type="submit" />
}

And in your HttpPost action, you can use the SelectedTask property value which will have the Id of the task selected

[HttpPost]
public ActionResult Create(TaskInstanceViewModel model)
{
    if (ModelState.IsValid)
    {
        var taskinstance = new TaskInstance { DueDate = model.DueDate ,
                                              TaskId=model.SelectedTask };
        db.TaskInstance.Add(taskinstance);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    model.TaskList = db.Task.ToList().Select(x => new SelectListItem
    {
        Value = x.Id.ToString(),
        Text = x.Name
    }).ToList();
    return View(model);
}
Sign up to request clarification or add additional context in comments.

Comments

1

It seems to me that you need you point to a property that represents the selected item in the dropdown. The dropdown items is IEnumerable<SelectListItem> why isn't the selected item a property of type SelectListItem?

Add a property to your view model:

public class TaskInstanceViewModel
{
   [DataType(DataType.DateTime)]
   public DateTime DueDate { get; set; }
   public int HowMany { get; set; }
   public IEnumerable<SelectListItem> TaskList { get; set; }

   public virtual ICollection<Task> Task { get; set; }

   //add this property:
   public SelectListItem SelectedItem { get; set; }

}

And modify the view:

@Html.DropDownListFor(x => Model.TaskList, Model.SelectedItem )

3 Comments

This make sense to me, I didn't realise that the second item in DropDownList() was what attribute it sets, however when trying to impliment this im getting the error: Argument 3: Cannot convert from '...SelectItemList' to '...IEnumerable<SelectItemList>'
then what is SelectListItem
Sorry, that was a typo on my part, both meant to be SelectListItem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.