简体   繁体   中英

Multiple Models in a single View: submit failure

I'm new to MVC C# and I'm still learning the basics. I was doing the guide at the link http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/ Way 6: "Using Render Action Method". But when I Insert Object, Post results were repeated not stop. Help me!

HomeController:

 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");
        }
    }

View "Index" :

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

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

"SavePost":

     @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"/>
            }

"ShowPost"

.....

RESULT: I can view Index Page successfully, but when I click submit, Post object insert to db repeat incessantly.

All child actions use their parent http method. So when you first call index method with get, child-renderactions makes http get request too. But when you submit and return index view, then all the child actions inside index view become post. So after submit, it calls http post save method. Then it returns index view. Then it calls again http post save...infinite loop. Best practices never return View() inside PostMethod. @{Html.RenderAction("SavePost","Home");} executes public ActionResult SavePost() when rendered by any get method executes public ActionResult SavePost(Post post)([HttpPost]) when rendered by any post method.

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

When you make this time, it redirects index action and child-actions inside index view become get request not post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM