you are passing datatype:json
while you are returning view from action, and another mistake is you are passing id in data attribute as well and in url as well, this is also wrong:
this should be:
$.ajax({
type: "POST",
url: '/Dashboard/Index/' + $(this).val(),
data: { id: $(this).val() },
dataType: "json",
error: function () {
alert("An error occurred.");
},
success: function (data) {
}
});
like this:
var id = $(this).val();
$.ajax({
type: "POST",
url: '@Url.Action("Index","Dashboard")',
data: { id: id },
error: function () {
alert("An error occurred.");
},
success: function (data) {
}
});
Note: Always use Url.Action helper you create the action url so that it will not create issues on live deployment.
if you want to return only object not view then do like this:
public ActionResult Index(int? id)
{
DashboardViewModel model = new DashboardViewModel();
if(id == null || id == 0)
{
User user = _userService.GetUserByID(Convert.ToInt32(User.Identity.GetUserId()));
model.SelectedUser = user;
}
else
{
model.SelectedUser = _userService.GetUserByID(id.Value);
}
return JsonResult(model,JsonRequestBehavior.AllowGet);
}
and then you have to put dataType:'json' in the ajax call.
Update:
Make ddl event like this:
$("#SelectedUserID").change(function(){
ChangeEventOfDDL($(this).val());
});
your function:
function ChangeEventOfDDL(id)
{
$.ajax({
type: "POST",
url: '@Url.Action("Index","Dashboard")',
data: { id: id },
error: function () {
alert("An error occurred.");
},
success: function (data) {
}
});
}