I am using asp.net mvc 4 web app c#. I have the following model:
public class Job
{
public int id { get; set; }
public string description { get; set; }
public string company { get; set; }
public JobType jobType { get; set; }
//public int JobTypeId { get { return this.jobType.id; } }
}
Now I want to write a create action where the jobType attribute is set through a DropDownList. The create action:
//
// GET: /Job/Create
public ActionResult Create()
{
IEnumerable<JobType> jobtypes = db.JobTypes.ToList();
ViewData.Add("jobTypeList", new SelectList(jobtypes , "id", "name"));
return View();
}
//
// POST: /Job/Create
[HttpPost]
public ActionResult Create(Job job)
{
if (ModelState.IsValid)
{
db.Jobs.Add(job);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(job);
}
View:
<div class="editor-label">
@Html.LabelFor(model => model.jobType)
</div>
<div class="editor-field">
@Html.DropDownList("jobTypeList")
@Html.ValidationMessageFor(model => model.jobType)
</div>
The DropDownList is working fine listing existing jobtypes. However, when a job is created the jobetype of the job is not set (the jobtype id is not set in the job row of the created job). As I am new to asp.net mvc, I am not sure what the form passes to the post create action: Does it pass the jobtype object or the jobtype id? Why does it not set the jobtype id for the created job? Do I have to set the jobtype id my self in post create action? If so how do I get the selected value of the DropDownList?
EDIT:
So to get the id of the selected value in the drop-down list, I just have a line like this:
where the function getId() takes a name (the value in the drop-down) and then does a database query for the id of the department selected. Here is my getID() function
Note: You don’t need the whole APIFactory thing for this, you could just throw the query in instead of the line I have, and it would work just as well. However, if you are using the same queries a lot, I would recommend it.
EDIT:
Since you are using a cshtml page and not a aspx page, use the method described here to get the value, and then my method to get the id:
How to get Dropdownlist selected value