Jyotish Singh Jyotish Singh - 1 month ago 15
Ajax Question

JQuery is working fine with integer but not with string in MVC 5

Jquery is working perfectly fine with integer var but got error for string. My code is as below.

@section Scripts {
<script type="text/javascript">
$(function () {
$.getJSON('/Service/ListServiceType', function (result) {
var ddl = $('#ServiceType');
var type = @Model.Type;
ddl.empty();
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Type)
.text(this.Type)
.appendTo(ddl);
});
$("#ServiceType").find("option").each(function () {
alert($(this).val())
if ($(this).val() == type) {

$(this).prop("selected", "selected");
}
});
});

$.getJSON('/Category/ListCategory', function (result) {
var ddl = $('#CategoryType');
var id = @Model.CategoryId;
ddl.empty();
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Name)
.appendTo(ddl);
});
$("#CategoryType").find("option").each(function () {

if ($(this).val() == id) {

$(this).prop("selected", "selected");
}
});
});
});

</script>
}


Lower part(/Category/ListCategory)works perfectly fine but not the upper one. As I am new in JQuery and Javascript so a little help would be appreciable.

Answer

String type should be in quotes.

Change this

var type =  @Model.Type; 

to

var type =  '@Model.Type';
Comments