1

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 });
        }
2
  • 1
    If HTTP status is 500, then what is the exception message? Commented Jul 19, 2016 at 14:44
  • why is not possible to use Ajax.BeginForm method? Commented Jul 19, 2016 at 14:46

1 Answer 1

1

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.

You specified the contentType as "application/json" .But you are sending the javascript object as it is. So your request payload will be sent as something like

Name=SomeNameValue&Url=SomeUrlValue And with your current server code, the model binder cannot map it to an object of SettingProfile.

The solution is to send 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");
        };

Now your client code will send a request payload like

{"Name":"SomeName","Url":"SomeUrl"}

and model binder will be able to map it properly.

If it is simple data, you can simply not mention a custom contentType and send the js object as it is. jQuery will use the default contentType value which is "application/x-www-form-urlencoded" and model binding will work.

So the below code will work fine.

  jQuery.ajax({
                url: "@Url.Action("Create", "SettingProfile")",
                method: "POST",
                data:settingProfile
        })

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Yustx I initially approved(I have to be carefully reading stuff) and rolled back your edit. JSON.stringify is not needed. The whole point i was trying to make was, the code will work without it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.