MVC 将子级添加到父级
假设我有一个子对象和父对象,每个对象都有一个存储库和一个控制器。
更新:父对象有许多子对象。
父级的创建控制器看起来像这样。要创建的帖子将使用自动生成的表单进行。
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Parent parent)
{
var parentRepo = new ParentRepository();
parentRepo.Save(parent);
return View();
}
创建父级后,我将如何创建子级?
1) 一种解决方案是使用像 child/create/{idParent} 这样的 url
2) 甚至将父 ID 嵌入子创建表单中,以便将其与其余子数据一起发布。
两者似乎都不符合 MVC 的精神。
assuming I have a Child and Parent object each of which has a repository and a controller.
Update: A Parent has many Child objects.
the parent's controller for creating would look something like. the post to create will be made using the auto-generated form.
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Parent parent)
{
var parentRepo = new ParentRepository();
parentRepo.Save(parent);
return View();
}
how would I go creating a child after I have created the parent?
1) one solution would be using a url like child/create/{idParent}
2) or even embedding the parent id in the child creating form so it is posted with the rest of the child data.
Both seem not in the spirit of MVC.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会选择替代方案1)
在您的创建父级的发布版本中,您可以返回一个RedirectAction来创建子级(并在您的routeValues中添加idParent)。如果您不喜欢 url Child/Create/{idParent},您可以使用类似 Parent/{idParent}/CreateChild 的内容,具体取决于它如何匹配您的控制器设置,以及上下文中的主要实体是什么(Child in第一个 url,第二个 url 中的父级)。
I would go with alternative 1)
In your Post version of Create parent, you can return a RedirectAction to creating a child (and add the idParent in your routeValues). If you don't like the url Child/Create/{idParent}, you could have something like Parent/{idParent}/CreateChild, depending on how it matches your controller setup, and what the main entity in your context is (Child in the first url, Parent in the second url).
如果这确实需要一个两步过程,那么我认为您的网址没有错误。
它将允许用户通过按 F5 来刷新浏览器,并且刷新后他仍然可以输入数据。显示子对象的错误消息也很容易。
但我不确定这两个步骤是否真的有必要。如果您有机会通过 1 个操作构建完整的对象,那就会更容易。但我只是猜测。也许这是一个设计决定。
If this realy needs to be a 2 step process then I don't think the url you have is wrong.
It would allow the user to refresh his browser by hitting F5 and he would still be able to enter data after refreshing. It would also be easy to display errormessages for the child object.
But I am not shure if this 2 step process is realy necessary. If you have the chance to build the complete object on 1 action it would be easier. But I am just guessing. Maybe its a design decission.