I have an mvc razor form. What i want is to submit the user's selection from Items dropdown list and navigate to Details view in order to access the chosen item's information.
Currently when i click the submit button i navigate succesfully to Details view but there is absolutely no data showing there.
Can you please help me?
View
@using (Html.BeginForm("Details", "Bookings", FormMethod.Post))
{
<fieldset>
<legend> Type/Item</legend>
<label for="Items">Item Types </label>
@Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new { id = "ItemTypeID" })
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script type="text/javascript">
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '@Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
}
});
});
</script>
Controller:
public ActionResult Details(string id)
{
var item = db.Items.Find(id);
return View(item);
}
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId
select new { Value = s.ItemName, ItemsID = s.ItemId };
return Json(data);
}
A dropdown only sends simple values. The name usually have to match the name of the parameter in the method signature. Remember that it is the name attribute that is the key in the querystring, and not the id attribute. Hence the use of department in this example and Items in @Murali's answer.
Try changing your details method to:
use
Items
in Details method if you want to get Items value