【发布时间】:2015-10-20 06:36:44
【问题描述】:
我有一个使用 html 控件的 asp.net 网页。我想通过使用 web 方法发送输入值代码隐藏到数据库中,并且我希望页面不刷新。所以我使用了 Ajax。 在 Ajax 中,succeed 函数失败并返回 undefined。
default.aspx:
<form id="form1" runat="server">
<input id="hName" name="hName" type="text" />
<input id="hSurname" name="hSurname" type="text" />
<input id="hPhone" name="hPhone" type="text" />
<input id="rNote" name="rNote" type="text" />
<select id="rTypeSelect">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<input type="button" value="Save" id="btnSaveAppointment" name="btnSaveAppointment"/>
</form>
jQuery:
$("#btnSaveAppointment").live('click', function (event) {
name = $('#hName').val();
surname = $('#hSurname').val();
phone = $('#hPhone').val();
note = $('#rNote').val();
type = $("#rTypeSelect option:selected").text();
rdate = '01.09.2015';
rhour = '09.30';
var appointment= {};
appointment= {
_name: name,
_surname: surname,
_phone: phone,
_note: note,
_type: type,
_rdate: rdate,
_rhour: rhour
}
$.ajax({
type: 'POST',
url: '../saveAppointment.aspx/save',
data: { appointment: JSON.stringify(appointment) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (result) {
alert(result);
},
error: function () {
alert('Error!' + result.d);
}
});
});
saveAppointment.aspx 网络方法:
public partial class saveAppointment : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string save(string jsondata)
{
var output = JsonConvert.DeserializeObject<Appointment>(jsondata);
Appointment r = (Appointment)output;
r.Name= output.rName.ToString();
//sql code here
return r.Name;
}
这是类:
public class Appointment
{
public int ID { get; set; }
public string rName{ get; set; }
public string rSurname { get; set; }
public string rPhone{ get; set; }
public string rNote{ get; set; }
public string rType{ get; set; }
public DateTime rDate{ get; set; }
public DateTime rHour{ get; set; }
}
当我删除 WebMethod 的参数(字符串 jsondata)时,Ajax 成功函数不会失败。但是当我输入 json 参数时,它失败了。请告诉我哪里做错了,谢谢!
【问题讨论】:
标签: jquery asp.net ajax json webmethod