Reputation: 1680
I am trying to have a dropdownlist on Create.chtml where a user can select a 'NAME' from the dropdownlist and the corresponding value (ID) should be sent back to controller to add it to the database table.
What is working: I can see the dropdownlist with NAMES on the Create.chtml view page
What is NOT working: when a NAME is selected from the dropdownlist in the view, its value (ID) is not passed to Controller
Please see the code below to identify where I might be doing it wrong.
Controller:
//
// GET: /OrganizationCodes/Create
public ActionResult Create()
{
var orgzList = (from x in db.TABLE_ORGANIZATIONS
select new TABLE_ORGANIZATIONSDTO
{
ID = x.ID,
NAME = x.NAME
}).OrderBy(w => w.NAME).ToList();
ViewBag.orgz = new SelectList(orgzList, "ID", "NAME");
return View();
}
public class TABLE_ORGANIZATIONSDTO
{
public string NAME { get; set; }
public int ID { get; set; }
}
//
// POST: /OrganizationCodes/Create
[HttpPost]
public ActionResult Create(TABLE_CODES dp)
{
try
{
using (var db = new IngestEntities())
{
TABLE_CODES codes_temp = new TABLE_CODES();
ViewBag.orgz = codes_temp;
db.AddToTABLE_CODES(dp);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
===================================================================================
View: 'Create.chtml'
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
@Html.DropDownList("orgz", (SelectList)ViewBag.orgz)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Edit 1:
Edit 2:
I am trying to have a view with a dropdownlist of NAMES with value as ID from table 'TABLE_ORGANIZATIONS' which should be added to table 'TABLE_CODES' -> 'MANAGER' column as a number
Upvotes: 1
Views: 3080
Reputation: 36043
On your action Create
, [HttpPost]
version, in which variable are you expecting to see the value of your selected name?
You've named your <select>
element with id = "orgz", but you don't have a parameter to your action method named "orgz".
Edit:
When you do:
@Html.DropDownList("orgz", (SelectList)ViewBag.orgz)
You're going to end up with HTML like this:
<select id="orgz" name="orgz">...</select>
When the form is posted back to the controller action, it will try to find a variable called "orgz" that it will put the selected item from your <select>
element into. You are missing this.
Try changing your [HttpPost]
version of Create
to include an "orgz" variable:
public ActionResult Create(TABLE_CODES dp, int orgz)
{
// orgz will contain the ID of the selected item
}
Then your variable "orgz" will contain the ID of the selected item from your drop down list.
Upvotes: 3