在ASP.MVC中发送表单数据

时间:2016-05-06 13:19:46

标签: asp.net-mvc

我的表格如下。当我发送表单时,数据(id,content,gdate)到达ActionResult后。但是,一个字段(名为“category”)在post侧变为null。缺少的部分是什么?

BlogPost模型:

 public class BlogPost
{
    public virtual string Id { get; set; }
    public virtual string content { get; set; }
    public virtual string gdate { get; set; }
    public virtual Category Category { get; set; }

}

类别模型:

public class Category
{
    public int ID{ get; set; }
    public string Name{ get; set; }
}

视图模型:

 public class CreateVM
{        
    public BlogPost BlogPost { get; 
    public IEnumerable<SelectListItem> Categories;
}

控制器:

// GET: BlogPosts/Create
    public ActionResult Create()
    {
        CreateVM vm = new CreateVM();
        vm.Categories = new SelectList(db.Categories, "ID", "Name");
        return View(vm);
    }


        return View(vm);
    }

[HttpPost]    
public ActionResult Create(CreateVM vm)
        {
            if (ModelState.IsValid)
            {
                db.BlogPosts.Add(vm.BlogPost);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

查看:

@Html.DropDownListFor(model => model.BlogPost.Category, Model.Categories);

2 个答案:

答案 0 :(得分:1)

更改你的助手:

@Html.DropDownListFor(model => model.BlogPost.Category.ID, Model.Categories);

它将在帖子上绑定选定的Id

然后更改控制器以从db获取现有实体:

[HttpPost]    
public ActionResult Create(CreateVM vm)
{
    if (ModelState.IsValid)
    {
        // this is the line where you should get your category entoty from DB. MAby you have different tables. it just example
        vm.BlogPost.Category = db.Categories.FirstOrDefault(x => x.ID == vm.BlogPost.Category.ID)
        db.BlogPosts.Add(vm.BlogPost);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}

答案 1 :(得分:1)

我已经修改了你的模型和视图以使事情有效..

视图模型:

public class CreateVM
{        
public BlogPost BlogPost { get; set;}
public IEnumerable<SelectListItem> Categories{ get; set;}
public int CategoryId{ get; set;}
}

查看:

 @Html.DropDownListFor(model => model.CategoryId, new SelectList(Model.Categories, "ID", "Name"));

注意:类别字段仍然只返回空值,但是在发布表单时,您将看到下拉列表的选定Id值被相应的一个填充,这将有助于进一步处理事物..