gpt4 book ai didi

c# - 单个 View 中的多个模型 : submit failure

转载 作者:行者123 更新时间:2023-11-30 16:53:09 24 4
gpt4 key购买 nike

我是 MVC C# 的新手,我仍在学习基础知识。我在链接 http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/ 上做指南方式 6:“使用渲染操作方法”。但是当我Insert Object的时候,Post的结果却不停的重复。帮帮我!

家庭 Controller :

 public ActionResult Index()
{
return View();
}
public PartialViewResult ShowPost() {
.......
return PartialView(Posts);
}

public PartialViewResult SavePost()
{

return PartialView("SavePost", new Post());
}
[HttpPost]
public PartialViewResult SavePost(Post post)
{
if (ModelState.IsValid)
{
repository.Insert(post);
return PartialView("Index");//?????????
}
else
{
return PartialView("Index");
}
}

查看“索引”:

              @{Html.RenderAction("SavePost","Home");}

@{Html.RenderAction("ShowPost","Home");}

“保存帖子”:

     @model ERichLink.Domain.Entities.Post

@using (Html.BeginForm("SavePost", "Home",FormMethod.Post))
{
@Html.TextBoxFor(model => model.Title)
@Html.TextBoxFor(model => model.CategoryID)
@Html.TextBoxFor(model => model.Description)
<input id="post_btn" value="post"type="submit"/>
}

“展示贴”

.....

结果:我可以成功查看索引页,但是当我单击提交时,Post 对象不断地插入到数据库中。

最佳答案

所有子操作都使用它们的父 http 方法。因此,当您第一次使用 get 调用 index 方法时,child-renderactions 也会发出 http get 请求。但是,当您提交并返回索引 View 时,索引 View 中的所有子操作都会变成帖子。所以提交后,它会调用http post 保存方法。然后它返回索引 View 。然后它再次调用 http post save...无限循环。最佳实践从不在 PostMethod 中返回 View()。@{Html.RenderAction("SavePost","Home");} 执行 public ActionResult SavePost()当通过任何 get 方法呈现时执行 public ActionResult SavePost( Post post)([HttpPost]) 当由任何 post 方法呈现时。

    [HttpPost]
public ActionResult SavePost(Post post)
{
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("index");
}

当您这次创建时,它会将索引操作和索引 View 内的子操作重定向为获取请求而不是发布。

关于c# - 单个 View 中的多个模型 : submit failure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com