【问题标题】:How to read ajax parameters in asp mvc model binder如何在asp mvc模型绑定器中读取ajax参数
【发布时间】:2015-06-12 20:31:06
【问题描述】:

我有角度服务:

statistics.factory('getData', function ($http) {
return {
    result: function (url, date) {
        return $http({
            method: 'POST',
            url: url,
            data: {
                date: date
            }
        });
    }
};});

此服务发送给 MVC 控制器的日期参数。

我想在 MVC Model Bidned 中查看 data 参数。

我试过了:

 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        var date = request["date"];
        var date1 = request.Form.Get("date");
        var date3 = new StreamReader(request.InputStream);
        var requestFromPost = date3.ReadToEnd();

    }

但我总是得到空值。

这是我的模型绑定器:

public class DataBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var date = request.QueryString["date"];

        return date;
    }

和行动

[HttpPost]
public ActionResult GetStatisticsData([ModelBinder(typeof(DataBinder))] DataA dataA)

}

【问题讨论】:

  • 您可能需要检查查询字符串:var date = request.QueryString["date"];
  • 你能检查“日期”在 ajax 参数中是否未定义吗? -
  • 当然,当我有这样的操作时: [HttpPost] public ActionResult GetStatisticsData(string date) } 它工作正常
  • null 到底是什么,var request 还是获取var date 的请求?

标签: asp.net-mvc angularjs


【解决方案1】:

对于您的第一个 BindModel 实现,您没有返回任何对象,因此它是无效的,第二个至少是有效的,但是您试图从错误的集合中获取 date 值,它应该是 @ 987654324@ 不是QueryString 并且当您在期望类型DataA 的Action 中绑定时还返回object。所以以下是它应该是什么(不包括必要的检查和本地化):

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var date = DateTime.Parse(controllerContext.HttpContext.Request.Form["date"]);
    return new DataA 
    {
        SomeDate = date
    };
}

我还根据您的问题here 发布了一个解决方案,您会看到它正在运行。我使用 jquery 而不是 angular 来快速给出答案,但请求与 $http 相同。希望对您有所帮助,如有更多问题请追问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2010-10-13
    • 2020-04-18
    相关资源
    最近更新 更多