I want to show Course Code after selecting a department from drop down. it searches from database and get but does not show at browser. Here is the drop down:
<select name="Id" id="Id">
<option value="">Select Department</option>
@foreach (var departments in ViewBag.ShowDepartments)
{
<option value="@departments.Id">@departments.Name</option>
}
</select>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#Id").change(function() {
var departmentId = $("#Id").val();
var json = { departmentId: departmentId };
$.ajax({
type: "POST",
url: '@Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
//$("#myTable").append('<tr><th>ID</th><th>Name</th></tr>');
$('#Code').val(data.Code);
//$('#ContactNo').val(data.ContactNo);
//$('#Type').val(data.Type);
}
});
});
});
</script>
I am using mvc.
Your code should work fine as long as ViewAllScheduleByDept
action method returns a json structure with a Code
property.
[HttpPost]
public ActionResult ViewAllScheduleByDept(int departmentId)
{
//values hardcoded for demo. you may replace it value from db table(s)
return Json( new { Code="HardcodedValue", ContactNo="12345"} );
}
and you have an input form element with Id property value as Code in your page
<input type="text" id="Code" />
and you do not have any other script errors which is preventing your js code to execute.
Also, since you are sending just the Id value, you don't really need to use JSON.stringify
method and no need to specify contentType
property value.
$("#Id").change(function () {
$.ajax({
type: "POST",
url: '@Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
data: { departmentId: $("#Id").val() },
success: function (data) {
alert(data.Code);
$('#Code').val(data.Code);
}
,error:function(a, b, c) {
alert("Error" + c);
}
});
});