【问题标题】:.NET MVC 4 HTTP Post Data as JSON object.NET MVC 4 HTTP Post 数据作为 JSON 对象
【发布时间】:2014-02-21 01:52:16
【问题描述】:

我正在尝试创建一个简单的博客应用程序,并且我的注册和登录功能运行良好。问题是,在创建“博客”条目时,博客有一个名为标签的自定义控件,它只是该博客文章的标签数组。但是,Razor 引擎没有类似@Html.ControlFor() 的列表,所以我劫持了表单并使用 JSON 进行自己的 AJAX 调用:

{ 
  "Title" : "mytitle",
  "Content" : "some content",
  "Tags" : ["tag1", "tag2", "tag3"]
}

我有一个如下所示的 BlogViewModel:

public class BlogViewModel
    {
        [Required]
        [Display(Name = "Title")]
        public string Title { get; set; }

        [Required]
        [Display(Name = "Content")]
        public string Content { get; set; }

        public List<Tag> Tags { get; set; }
    }

还有一个控制器动作:

[HttpPost]
        public ActionResult Create(BlogViewModel bvm)
        {
           /* This is where I want to build of a BlogEntry object and save it to the DB */

            return RedirectToAction("Index");
        }

问题是我在 PostBack 中的 BlogViewModel 出于某种原因除了 Title 属性之外的所有值都是空值。处理上述 JSON 对象以便我可以正确保存 BlogEntry 的正确方法是什么?

【问题讨论】:

  • 你使用什么机制来反序列化 json 字符串?
  • 我现在没有反序列化任何东西。我正在尝试找出最好的方法。我是否将 JSON 序列化为客户端上的字符串?还是我直接发送 JSON 对象?这是我不知道的

标签: c# .net json asp.net-mvc-4 razor


【解决方案1】:

实际上有一种方法可以通过 Razor 绑定到模型。以下是你的做法:

@for (int i = 0; i < Model.Tags.Count; i++)
{
    @Html.TextboxFor(model => model.Tags[i].TagName)
}

假设您的标签模型如下所示:

public class Tag
{
    public string TagName { get; set; }
}

这会将标签集合绑定到您的模型。但是我不确定这是解决问题的正确方法,因为我假设您想动态添加 X 多个标签。对吧?

【讨论】:

  • 是的,但是在创建博客时,Model.Tags.Count 为 0.. 那么如何创建一个新的呢。
  • 就像我说的,如果您要动态添加它们,那么最好的办法是使用一些现有的 jquery 标签库,例如:welldonethings.com/tags/manageraehlke.github.io/tag-it
【解决方案2】:

试试这个:-

使用IModelBinder接口

public class Tag
{
    public string TagName { get; set; }
}

[Serializable()]
public class BlogViewModel
{
    [Required]
    [Display(Name = "Title")]
    public string Title { get; set; }

    [Required]
    [Display(Name = "Content")]
    public string Content { get; set; }

    public List<Tag> Tags { get; set; }
}

public class BlogViewModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        BlogViewModel model;

        if (controllerContext.RequestContext.HttpContext.Request.AcceptTypes.Contains("application/json"))
        {
            var serializer = new JavaScriptSerializer();
            var form = controllerContext.RequestContext.HttpContext.Request.Form.ToString();
            model = serializer.Deserialize<BlogViewModel>(HttpUtility.UrlDecode(form));
        }
        else
        {
            model = (BlogViewModel)ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
        }

        return model;
    }
}

JS:-

<script type="text/javascript">
    var $tags = [];

    var tag = function (TagName) {
        this.TagName = TagName;
    }

    $tags.push(new tag("a"));
    $tags.push(new tag("b"));
    $tags.push(new tag("c"));

    jQuery(function ($) {
        $.ajax({
            url:"http://localhost:3938/Blog/Create",
            ContentType: "application/json; charset=utf-8",
            dataType:"json",
            type: "post",
            data:JSON.stringify({ 
                        "Title" : "mytitle",
                        "Content" : "some content",
                        "Tags": $tags
                    })
        });
    });

</script>

在 Global.asax.cs 文件中添加 ModelBinders.Binders[typeof(BlogViewModel)] = new BlogViewModelBinder();

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ModelBinders.Binders[typeof(BlogViewModel)] = new BlogViewModelBinder();
    }
}

【讨论】:

  • @MattHintzke 这能回答您的问题吗?
【解决方案3】:

尝试将其添加到您的 ajax 调用中。

data: JSON.stringify(model),
contentType: 'application/json'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2017-05-03
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多