MVC EF - 如何将Array保存到db

时间:2018-01-09 02:20:13

标签: arrays json entity-framework asp.net-mvc-4

我需要保存一个标签数组,我使用angular和json从视图传递给控制器​​。我尝试了以下内容,但vm.Name出现为null。

脚本发布请求

$http({
method: 'POST',
url: '/RecipeTags/CreateRecipeTag',
data: $scope.selectedTags
}).then(function (response) {
}, function () { alert('Error CreateRecipeTag'); });

示例数组

[{"Id":12,"Name":"Baking","RecipeId":0},{"Id":16,"Name":"Oriental","RecipeId":0},{"Id":17,"Name":"Japanese","RecipeId":0}]

RecipeTagsController.cs

[HttpPost]
    public JsonResult CreateRecipeTag(List<RecipeTag> vm)
    {

        foreach (var tag in vm)
        {
            RecipeTag recipeTag = new RecipeTag();
            recipeTag.Name = vm.Name;
            recipeTag.RecipeId = vm.RecipeId;
            db.RecipeTags.Add(recipeTag);
        }
        db.SaveChanges();
        return Json(vm, JsonRequestBehavior.AllowGet);
    }

RecipeTag.cs​​

public class RecipeTag
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

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

    [ForeignKey("Recipe")]
    public int RecipeId { get; set; }
    public virtual Recipe Recipe { get; set; }
}

2 个答案:

答案 0 :(得分:0)

您必须将RecipeTag定义为DataContract。

这样的事情:

// Service definition
[ServiceContract(Name = "Service1")]
public interface IMyService
{
    [OperationContract,HttpPost]
    public JsonResult CreateRecipeTag(List<MyRecipeTag> vm);
}

// DataType-Definition for the Service
[DataContract]
public class MyRecipeTag
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int RecipeId { get; set; }
    public virtual Recipe Recipe { get; set; }
}

// Service implementation
public class MyService : IMyService
{
    [HttpPost]
    public JsonResult CreateRecipeTag(List<RecipeTag> vm)
    {

        foreach (var tag in vm)
        {
            RecipeTag recipeTag = new RecipeTag();
            recipeTag.Name = tag.Name;
            recipeTag.RecipeId = tag.RecipeId;
            db.RecipeTags.Add(tag);
        }
        db.SaveChanges();
        return Json(vm, JsonRequestBehavior.AllowGet);
    }
}

通过这个,您可以定义函数的类。这个类可以与EF兼容,或者你将字段复制到你的CalipeTag。

答案 1 :(得分:0)

就像@Jasen说我将动作签名更改为集合并将vm.RecipeId更改为tag.RecipeId并且我也使ActionResult异步并且它最终有效!谢谢!

[HttpPost]
        public async Task<ActionResult> CreateRecipeTag([Bind(Include = "Id,Name,RecipeId")] List<RecipeTag> vm)
        {
            foreach (var tag in vm)
            {
                RecipeTag recipeTag = new RecipeTag();
                recipeTag.RecipeId = tag.RecipeId;
                recipeTag.Name = tag.Name;
                db.RecipeTags.Add(recipeTag);
                await db.SaveChangesAsync();
            }
            return RedirectToAction("Index");
        }