【发布时间】:2016-11-22 12:46:22
【问题描述】:
目前我可以定期创建模型(通过 SettingProfile/Create)
但是当我尝试使用 AJAX 发送包装在 settingProfile JS 对象中的数据时,它返回 HTTP 500 Internal Server Error 错误,我相信问题出在数据类型上。在 AJAX 中调用 Create 方法的正确方法是什么?
我的代码:
型号:
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; }
}
查看(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");
});
}
控制器:
[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 });
}
【问题讨论】:
-
如果HTTP状态为500,那么异常信息是什么?
-
为什么不能使用Ajax.BeginForm方法?
标签: c# jquery ajax asp.net-mvc model-binding