Cannot get my html input array to serialize into a List<string> in Asp.Net mvc

痞子三分冷 提交于 2019-12-11 07:16:26

问题


I am attempting to implement a tagging system into my asp.net MVC project. When a user edits or adds a task, they can add any amount of tags they want before submitting. I am using the Jquery Tagit plugin, so when a user adds a new tag an input field is created that looks like:

<input type="hidden" style="display:none;" value="tag1" name="Tags[]">

When the user presses the submit button after adding a few tags, the browser sends the following querystring to the server (retrieved via fiddler):

IsNew=True&Id=2222&Title=Test+Title&Description=Test+Description&Tags%5B%5D=Tag1&Tags%5B%5D=blah&Tags%5B%5D=another-tag

Now my viewmodel that I am serializing this data into has the following structure:

public class KnowledgeBaseTaskViewModel
{
    public int Id { get; set; }

    [Required(AllowEmptyStrings=false, ErrorMessage="Task title is required")]
    [StringLength(500)]
    public string Title { get; set; }

    [Required(AllowEmptyStrings=false, ErrorMessage="Task description is required")]
    [StringLength(500)]
    public string Description { get; set; }

    public List<string> Tags { get; set; }
    public bool IsNew { get; set; } // Needed to determine if we are inserting or not
}

Finally my receiving action has the following signature:

    [HttpPost]
    public ActionResult EditTask(KnowledgeBaseTaskViewModel task)

The issue is that my tag list is not serializing correctly, and my List Tags is null. I have looked at various questions on this site on how to serialize arrays but I still cannot see what I am doing wrong. Any help is greatly appreciated.


回答1:


It sounds like what you've got should work, but try changing the type of Tags property from List to IList. the model binder might not be using the concrete List<> type.

also, check out this article by Phil Haack: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx



来源:https://stackoverflow.com/questions/3317981/cannot-get-my-html-input-array-to-serialize-into-a-liststring-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!