Yustx Yustx - 4 months ago 15
jQuery Question

How do I create a model using AJAX in ASP.NET MVC 5

Currently I can to create models regularly (by going SettingProfile/Create)

But when I try to use AJAX to send data wrapped in settingProfile JS object it returns HTTP 500 Internal Server Error error, I believe problem is in the data type. What would be correct way of calling Create method in AJAX?

My code:

Model:

public class SettingProfile
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
public long? UserId { get; set; }
public string Url { get; set; }
}


View (JS):

function saveSettingProfile() {
var name = prompt("Please enter profile name", "");
var url = $("form").serialize(); // Not AJAX url, its a variable in model

var settingProfile = {
Name: name,
Url: url
};

jQuery.ajax({
url: "@Url.Action("Create", "SettingProfile")",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
data: settingProfile
}).done(function (response) {
alert("Profile saved successfully");
}).fail(function () {
alert("Could not save profile");
});
}


Controller:

[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Name,Url")] SettingProfile settingProfile)
{
settingProfile.UserId = 8; // TODO: get user id from session
if (ModelState.IsValid)
{
db.SettingProfiles.Add(settingProfile);
db.SaveChanges();
return Json(new { success = true });
}
return Json(new { success = false });
}

Answer

500 error means, your server code is crashing. It could be of many reasons. One thing i noticed (which might cause a 500 error) is the way you are sending data.

Make sure you are sending the stringified version of your javascript object. You may use the JSON.stringify method to do so.

 jQuery.ajax({
                url: "@Url.Action("Create", "SettingProfile")",
                contentType: "application/json; charset=utf-8",
                method: "POST",
                data: JSON.stringify(settingProfile)
        }).done(function (response) {
            alert("Profile saved successfully");
        };

You may also check the browser's network tab and see the response coming back from the server for that ajax call. If an exception happens, you can see the details there.

Comments