Multiple Models in One View: Submit Failure

I am new to MVC C # and I am still learning the basics. I was doing a guide at http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/ Method 6: "Using a render action method". But when I insert the object, the publish results kept repeating without stopping. 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 the index page successfully, but when I click the submit button, Post object insert to db repeats constantly.

+3


source to share


1 answer


All child activities use their parent http method. So when you first call the index method with get, child-renderactions makes an http get request as well. But when you submit and return an index pointer, all child activities inside the index view become postal. So after submitting, it calls the post post post method. Then it returns the index. Then it calls HTTP post save ... infin loop again. Best practices never return View () inside PostMethod. @{Html.RenderAction("SavePost","Home");}

executes public ActionResult SavePost()

on rendering with any get method executes public ActionResult SavePost(Post post)([HttpPost])

on rendering with any post method.

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

      



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

+2


source







All Articles