Reputation: 47
I am new in Mvc jason I have following ajax function the function is working fine and sending data to server action and the server also returning success or failure but the problem is the JSON data is displayed in new page like
{"Success":true}
here is my ajax function
$('#save').click(function () {
var CourseID = $('.form-control span1').val();
var Type = $('.form-control span2').val();
var id [email protected]
$.ajax({
url: '@Url.Action("AdminUser/Edit")',
type: 'POST',
data: { id: '@Model.UserId', CourseID: CourseID, Type: Type },
Success: function (response) {
if (response.Success) {
alert("done");
}
else {
alert("Errror");
}
}
});
});
And here is my controller
[HttpPost]
public ActionResult Edit(int id, string CourseID, string type)
{
KBS_Virtual_TrainingEntities db = new KBS_Virtual_TrainingEntities();
var sc = (from course in db.CourseSubscriptions.ToList()
where course.Cours.ID.ToString() == CourseID && course.SubscriptionsType.ID.ToString() == type
select course).SingleOrDefault();
UserSubscription new_sub = new UserSubscription();
CourseSubscription sub_course = (CourseSubscription)sc;
if (sub_course != null)
{
new_sub.CourseSubscription = sub_course;
new_sub.CourseSubscriptionID = sub_course.ID;
new_sub.StartedDate = DateTime.Now;
new_sub.UserID = id;
db.UserSubscriptions.Add(new_sub);
db.SaveChanges();
return Json(new { Success = true });
}
return Json(new{Success = false});
}
Upvotes: 0
Views: 103
Reputation: 486
try this :
$('#save').click(function () {
var CourseID = $('.form-control span1').val();
var Type = $('.form-control span2').val();
var id [email protected]
$.ajax({
url: '@Url.Action("AdminUser/Edit")',
type: 'POST',
data: { id: '@Model.UserId', CourseID: CourseID, Type: Type },
Success: function (response) {
if (response.Success) {
alert("done");
}
else {
alert("Errror");
}
return false;
}
});
});
return false will stop the redirection of the page and add script bundle ~/bundles/jqueryval
Upvotes: 0
Reputation: 498
Try changing the return Json(new { Success = true });
into
return Json(new { });
How about triggering the false instead and make it true by default?
Upvotes: 1