MVC3 BeginForm not rendering <form> tags

2019-07-09 03:25发布

问题:

I have an issue with my view not rendering the opening and closing FORM tags. Below is the code to my controller

    [HttpGet, Authorize]
    public ActionResult Edit(long id)
    {
        Position position = positionRepository.GetPositionById(id);
        return View(position);
    }

And this is the code on my view (omitting the controls code)

@using (Html.BeginForm("Edit", "Position", new { area = "Stock", id = Model.PositionId }, FormMethod.Post, null)){}

When the page is called it renders the appropriate data but the HTML side does not include the opening and closing FORM tags which will be required in order to save the modifications. Any clue as to what I may be missing?

回答1:

On a similar thread, I found that another form tag may not be closed, or the new BeginForm is being rendered inside of another form tag.

To verify quickly, you can add </form> above your Html.BeginForm(...).



回答2:

I found the root cause to be my master page. When adding the master page I selected a standard master page NOT one from the MVC3 list!. I proceeded to delete the existing master page and added the proper one (from the MVC3 list) refreshed the page and the tags were rendered properly.



回答3:

When you have a partial view inside a view the form Id will not generate until the previous form is closed.The solution is to use BeginForm for all the partial views. When you have one partial view this will not work. The trick is to keep 2 partial views may be a dummy partial view only for the form closing purpose.



回答4:

To further expand on this issue, I found that Html.BeginForm() only works when you call @RenderBody() from the parent layout.

All of the content in our partial views is grouped into @sections defined by the master. Because of this, we were only calling @RenderPage() and @RenderSection, never @RenderBody().

Once we added a call to @RenderBody(), our form tags appeared (even though all of our content is still defined within sections and there is no "body" content to render...)

Hope this helps someone else... took me awhile to figure it out... this post provided the final key..