Reputation: 43
I have problem with my first MVC project. I'm trying to change values of DropDownList of surnames when select DropDownList of doctor types. I think my action is working. But I cannot use result in view. Here my codes:
$(function () {
$('select#mCB').change(function () {
var docId = $(this).val();
$.ajax({
dataType: 'json',
data: 'spec=' + docId,
method: 'GET',
url: 'LoadDoctors',
success: function (data) {
$.each(data, function (key, Docs) {
$('select#shCB').append('<option value="0">Select One</option>');
$.each(Docs, function (index, docc) {
$('select#shCB').append(
'<option value="' + docc.Id + '">' + docc.Name + '</option>');
});
});
},
error: function (docID) {
alert(' Error !');
}
});
});
});
Actions:
public static List<Docs> GetDoctorBySpec(string spec)
{
List<Docs> list = new List<Docs>();
string query = "select ID, Familiyasi, Speciality from Doktorlar where Speciality=@spec";
SqlConnection Connection = new SqlConnection(DataBase.ConnectionString);
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.Add("@spec", spec);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
list.Add(new Docs
{
Id = dr.GetString(0),
Name = dr.GetString(1)
});
}
return list;
}
enter code here
enter code here
[HttpGet]
public ActionResult LoadDoctors(string spec)
{
List<Docs> list = DoctorsService.GetDoctorBySpec(spec);
if (list == null)
{
return Json(null);
}
return Json(list);
}
And here my DropDownLists:
<div class="editor-label">
@Html.LabelFor(model => model.DoktorTuri)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.DoktorTuri, new SelectList(ViewBag.Vrachlar), new { @id = "mCB", @class = "vrachlar" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Shifokori)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Shifokori, Enumerable.Empty<SelectListItem>(), new { @id = "shCB", @class = "vrachlar" })
</div>
Where is my mistake? Thanks for answers
Upvotes: 4
Views: 28210
Reputation:
A 500 (Internal Server Error)
almost always means that your throwing an exception on the server. Best guess is in your case it's because your method
DoctorsService.GetDoctorBySpec(spec);
does not accept null
as a parameter and the value of spec
is null
because your never pass it value to the controller. As stann1 has noted your ajax option needs to be
data: {spec: docId},
In addition, you do not specify the JsonRequestBehavior.AllowGet
parameter which means the method will fail.
All of this can be easily determined by debugging your code, both on the server and by using your browser tools (in particular the Network
tab to see what is being sent and received along with error messages)
However this is only one of many problems with your code.
Firstly, unless Docs
contains only 2 properties (the values you need for the option's value
attribute and display text), your unnecessarily wasting bandwidth and degrading performance by sending a whole lot of data to the client which is never used. Instead, send a collection of anonymous objects
[HttpGet]
public ActionResult LoadDoctors(string spec)
{
List<Docs> list = DoctorsService.GetDoctorBySpec(spec);
if (list == null)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
var data = list.Select(d => new
{
Value = d.Id,
Text = d.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Next, your script will only ever generate multiple <option value="0">Select One</option>
elements (one for each item in the collection) because data
in $.each(data, function (key, Docs) {
is your collection, and Docs
is the item in the collection. Your second $.each()
function will never produce anything because Docs
is not a collection.
You script should be (note I have use the short version $.getJSON()
rather than the longer $.ajax()
and also used the default id
attributes generated by the html helpers - its not clear why you would want to change the id's using new { id = "mCB" }
?)
var url = '@Url.Action("LoadDoctors")'; // never hard code your url's
var shifokori = $('#Shifokori'); // cache it
$('#DoktorTuri').change(function () {
$.getJSON(url, { spec: $(this).val() }, function(data) {
if (!data) { // only necessary depending on the version of jquery
// oops
}
// clear existing options and append empty option with NULL value (not zero)
// so validation will work
shifokori.empty().append($('<option></option>').val('').text('Select One'));
$.each(data, function (index, doc) {
shifokori.append($('<option></option>').val(doc.Value).text(doc.Text));
});
}).fail(function (result) {
// oops
});
});
Upvotes: 5
Reputation: 635
The data param of the call needs to be a Javascript object literal:
$.ajax({
dataType: 'json',
data: {spec: docId},
method: 'GET',
....
});
Also, try to debug your controller and use a rest extension (or Fiddler) to test the payload, you would catch such error easily yourself ;)
Upvotes: 1