我刚刚开始MVC所以有很多困惑.每当我们在asp.net webform项目中通过jquery调用任何服务器端函数时,该方法必须是静态的,并且必须由webmethod属性修饰.所以我想知道在mvc的情况下适用相同的规则.
我有一个代码,但我没有测试它.
function getTradeContribs(id,pfid, nodedates) {
var data = {};
data.portfolioId = pfid;
data.nodedates = nodedates;
$.ajax({
type: "POST",
url: "/Portfolios/getTradeContribs/"+id,
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: parseTradeContribs,
error: function (error) {
alert("failed in opening XML file !!!");
}
});
}
Run Code Online (Sandbox Code Playgroud)
public string getTradeContribs(int id,string portfolioId, string nodedates)
{
string jsonTest = @" {""nodedates"": ""date"":""01/01/2012""}";
return jsonTest;
}
Run Code Online (Sandbox Code Playgroud)
从上面的代码我几乎没有问题1)mvc中存在多少类型的控制器方法2)url:"/ Portfolios/getTradeContribs",它是什么样的网址.投资组合是控制器名称,getTradeContribs是行动名称?如果没有那么getTradeContribs是一种什么样的方法.
3)getTradeContribs没有返回ActionResult为什么4)ActionResult的重要性是什么?5)为什么id作为查询字符串传递,其余数据作为json传递.它会如何运作?
请讨论这一点,因为我是mvc的新手
每当我们在asp.net webform项目中通过jquery调用任何服务器端函数时,该方法必须是静态的,并且必须由webmethod属性修饰.所以我想知道在mvc的情况下适用相同的规则.
一点都不.ASP.NET MVC是一种完全不同的模式.在ASP.NET MVC中,您使用返回操作结果的控制器操作(从ActionResult派生的类).因此,如果要返回JSON,只需定义一个返回a JsonResult并将模型传递给它的控制器操作:
public ActionResult GetTradeContribs(int id, string portfolioId, string nodedates)
{
var model = new
{
nodedates = "foo",
date = DateTime.Now
};
return Json(model, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
甚至更好地定义视图模型:
public class TradeContribsRequestViewModel
{
public int Id { get; set; }
public string PortfolioId { get; set; }
public string NodeDates { get; set; }
}
public class TradeContribsViewModel
{
public string NodeDates { get; set; }
public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后:
public ActionResult GetTradeContribs(TradeContribsRequestViewModel request)
{
var model = new TradeContribsViewModel
{
NodeDates = "foo",
Date = DateTime.Now
};
return Json(model, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET MVC将自动将模型序列化为JSON字符串并将其传递给视图.然后你可以使用ajax调用它:
$.ajax({
url: '@Url.Action("GetTradeContribs", "Portfolios")',
type: 'POST',
data: {
id: 123,
portfolioId: 'some id',
nodedates: 'some node dates'
},
success: function(result) {
// You could directly use the properties of the result object here
// like for example: alert(result.nodedates);
}
});
Run Code Online (Sandbox Code Playgroud)
绝对不应该像在原始getTradeContribs方法中那样硬编码JSON .这是已经由框架为您处理的基础架构管道.你需要关心的是定义:
| 归档时间: |
|
| 查看次数: |
7594 次 |
| 最近记录: |