mkt*_*two 5 c# asp.net ajax jquery json
这里是我的情况:我有一个UserBadge对象在ASP.NET中,它包含3个字段,作为一个User对象,Badge对象和boolean(isNotified),以检查用户是否已经通知赚取徽章.我在发送一个特定的问题,UserBadge从这个WebMethod():
[WebMethod()]
public static UserBadge Notify()
{
var db = new achievDb();
foreach (var uB in db.UserBadges)
{
if (System.Web.HttpContext.Current.User.Identity.Name == uB.User.UserName)
{
if (!uB.isNotified)
{
return uB;
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
对我的$.ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../NotifCodeBehind.aspx/Notify",
data: "{}",
complete: function (result) {
if (result) {
$("#notify").jGrowl("You've unlocked a badge!", { header: 'Yay', close: function () {
$.ajax({
type: "POST",
url: "../NotifCodeBehind.aspx/Notified",
data: "{}",
success: function (ub) { DoCallback(JSON.stringify(ub)); },
error: function () { DoCallback("NOPE!") }
});
}
})
};
function DoCallback(msg) {
alert(msg);
}
}
})
})
</script>
Run Code Online (Sandbox Code Playgroud)
然后回到另一个通知关闭后将其WebMethod()设置isNotified boolean为true:
[WebMethod()]
public static void Notified(UserBadge ub)
{
var db = new achievDb();
foreach (var userbadge in db.UserBadges)
{
if (userbadge.UserId == ub.UserId && userbadge.BadgeId == ub.UserId)
{
userbadge.isNotified = true;
db.SaveChanges();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题: 我完全不知道如何将对象实际传递给ajax,然后再回来......我花了大约1,5天浏览互联网,但是现在,我决定来救命.我读的越多,它就越困惑我,我是jQuery/Ajax/JSON的绝对新手.
因此,如果你能尽可能简单地保持它,并在正确的方向上推动我,那将是非常感激的!
编辑: 下面的新JavaScript,以为我有它,但我没有.
编辑2:
现在解决了,我最终使用的是控制器而不是WebMethods.
您希望使用JSON序列化.将结果返回到ajax回调方法时,Web方法可以以XML,JSON或字符串的形式返回结果.如果返回JSON,则复杂对象将以非常直接的方式转换为json对象.
假设你的班级结构
class UserBadge
{
User UserProperty { get; set; }
Badge BadgeProperty { get; set; }
bool IsNotified { get; set; }
}
class User
{
string Username { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
来自结果回调函数的javascript中的json对象将如下所示
{
UserProperty: { Username: "some username" },
BadgeProperty: { /**********/ },
IsNotified: true
}
Run Code Online (Sandbox Code Playgroud)
如您所见,您的JSON结构与您的类对象结构相同.所以,调用result.UserProperty.Usernamejavascript是完全可以的.构造同一个对象并将其传递给另一个ajax Web服务会将JSON对象转换为托管类对象.
编辑:您可以将ScriptMethodAttribute添加到WebMethod以指定JSON响应.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static UserBadge Notify()
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5368 次 |
| 最近记录: |