Search code examples
asp.net-mvc-4ajax.beginform

Ajax.ActionLink and Ajax.BeginForm with MVC Partial view


Im here so early again.sad I am implementing a tabbed based partial view in mvc4.. I have 3 tabs which displays 3 individual partial views wchich gets changed using Ajax.ActionLink. each of the Partial views are forms which needs to be posted to different actions within same controller. The ActionLinks are working fine{ partial views gets shown and changed}. I have used Ajax.BeginForm to submit the individual form so as to prevent full postback. On form submit the action gets called and implemented but My Challenge, I need to show the current form but with form cleared, currently d form contents retains- i.e redirecting to the same Partialview Below is my code

ProjectIndex Action of Project Controller.cs

[HttpPost]
        public PartialViewResult Projectindex(Project collection, int ProjId)
        {
            //Save collection to DB.            

            return PartialView("_Project");
        }

_Project.cshtml.. Partial View

@model MyProject.Models.Project

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Ajax.BeginForm("Projectindex", new { ProjId = "3" }, new AjaxOptions
{

    HttpMethod = "POST",
      OnBegin = "myonbegin",
    OnSuccess = "myonsuccess",
    OnComplete = "myoncomplete",
    OnFailure = "myonfailure",
    LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))

{   @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Project</legend>

        <div class="editor-label">
            @Html.EditorFor(model => model.ProjName)
        </div>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Project.cshtml Main View

@Ajax.ActionLink(
"Project",            //Link Text
"ProjectIndex",       //Public Method inside our Controller
new AjaxOptions
{
    HttpMethod = "GET",     //Do a HTTP Post
    InsertionMode = InsertionMode.Replace,  //Replace content
    UpdateTargetId = "TabBody",    //Target element ID
}
)

<div id="TabBody">
    @Html.Partial("_Project")
</div>

The only challenge is that the form doesnt get cleared giving me the impression that the view was not rendered.. I tried adding a OnSuccess and OnFailure option, but none gets fired.. Can someone point me in the right direction. Thanks in advance


Solution

  • I would just send back an empty model to the partial:

    public PartialViewResult Projectindex(Project collection, int ProjId)
    {
        //Save collection to DB.            
        var model = new Project();
        ModelState.Clear();
        return PartialView("_Project", model);
    }
    

    Added ModelState.Clear(), and I think this is really all that is needed.

    Forces the html helpers use your changed model. Otherwise they use the values from the form submit