关于json result的实例代码
16lz
2021-01-22
public JsonResult JsonData()
{
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(db.Weathers.ToList());
}
{
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(db.Weathers.ToList());
}
json方法有一个重构:
protected internal JsonResult Json(object data); protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
我们只需要使用第二种就行了,加上一个 json请求行为为Get方式就OK了
public JsonResult GetPersonInfo() { var person = new { Name = "张三", Age = 22, Sex = "男" }; return Json(person,JsonRequestBehavior.AllowGet); }
这样一来我们在前端就可以使用Get方式请求了:
view
$.ajax({ url: "/FriendLink/GetPersonInfo", type: "POST", dataType: "json", data: { }, success: function(data) { $("#friendContent").html(data.Name); } })
<!DOCTYPE html><html><head runat="server"><title>Index2</title><script src="\Scripts\jquery-1.10.2.min.js?1.1.11" type="text/javascript"></script><script type="text/javascript">var login = function () { $.ajax({ type: "post", url: "http://localhost:4968/Weathers/JsonData", data: null, success: function (res) { alert(JSON.stringify(res)); }, dataType: "json"}); }</script></head><body><div id="nav"><a href="/Home/Index">ajax+Handler</a> <a>ajax+action</a></div><div><h3>Login</h3><button type="button" onclick="login()">Submit</button></div></body></html>
更多相关文章
- 克隆对象的方法实例教程
- C# 中GUID生成格式有哪些方法
- 关于C#winform如何实现右下角弹出窗口结果的方法分享
- C#中如何格式化json字符串的方法分析
- C#中关于扩展方法的实例分析
- 如何限制所有HTTP请求是POST方式?
- Asp.net MVC 对输入的字符串字段做Trim处理的方法_实用技巧
- Asp.net MVC 对用户输入的字符串做Trim处理的方法实例
- .NET下关于log4net的使用方法的图文代码分享