43

Is there a way to submit a partial view form in asp.net mvc without reloading the parent page, but reloading the partial view only to its new state? Similar to how knockout.js updates using data-bind.

My data table renders with a variable number of columns/names so I don't think knockout.js is an option for this one, so I am trying to use a partial view instead.

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
Rayshawn
  • 2,603
  • 3
  • 27
  • 46

5 Answers5

59

Not without jQuery.

What you would have to do is put your Partial in a div, something like:

<div id="partial">
    @Html.Partial("YourPartial")
</div>

Then, to update (for example clicking a button with the id button), you could do:

$("#button").click(function () {
   $.ajax({
       url: "YourController/GetData",
       type: "get",
       data: $("form").serialize(), //if you need to post Model data, use this
       success: function (result) {
           $("#partial").html(result);
       }
   });
})

Then your action would look something like:

public ActionResult GetData(YourModel model) //that's if you need the model
{
    //do whatever

    return View(model);
}
aBlaze
  • 2,436
  • 2
  • 31
  • 63
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • This is a nice solution for someone who understands web development but not c# mvc. – Mustafa Oct 03 '17 at 20:24
  • @MurWade I'm sorry I don't understand why this solution would not be applicable to someone who's using MVC & C#?? Can you elaborate? – Joey Bob Oct 17 '17 at 11:20
  • 1
    @JoeyBob This is applicable to anyone using MVC & C#. You can do 1 thing in many ways and this way seems like the most understandable approach for someone who has done web developer(single page apps, ajax etc) but not mvc c#. with mvc c# you can also use update panel but that is not as straight forward as this. – Mustafa Oct 17 '17 at 20:13
13

Actually, if your Partial has a child action method, you can post (or even use an anchor link) directly to the child action and get an Ajax-like affect. We do this in several Views.

The syntax is

@Html.Action("MyPartial")

The Child Action is

public ActionResult MyPartial()
{
    return PartialView(Model);
}

If your form posts to the child action

@using (Html.BeginForm("MyPartial"))
{
    ...
}

The Partial View will be updated with the partial view returned from the child action.

Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.

Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
  • Trying this one out as well. – Rayshawn Feb 28 '13 at 23:22
  • Dave, can you expand on how this works? I would have expected this to result in the partial view returned from the posted form being shown as a new page rather than updated in place. – JohnnyHK Mar 01 '13 at 15:02
  • @JohnnyHK, I would have expected that too. surprisingly, this results in the Partial View being returned to the Parent View not in place of the Parent View. Having an effect like an Ajax call. – Dave Alperovich Mar 01 '13 at 15:14
  • this seems easy enough, except that I don't understand :) Where does the **@Html.Action("MyPartial")** go – Alin I Mar 27 '17 at 11:41
  • 3
    In MVC5 `Html.BeginForm("string")` invokes the extension overload `BeginForm(this HtmlHelper htmlHelper, object routeValues)` and results in a [`POST /?Length=N`](https://stackoverflow.com/questions/4357856/razor-actionlink-autogenerating-length-7-in-url). I feel that this answer "works" is unintended behavior. – Jasen Jul 08 '17 at 21:03
  • @Dave sorry to come back to this issue. I have a 'modal dialog' display. In the its .cshtml, I did a @Html.Partial(...) of my new partial view that contains nothing more than a form. So far so good. When I post the form, I get back a full page that wipes out the original page and modal dialog. My post back returns a PartialView("_viewName"). What I don't understand is the @Html.Action() that you have in your answer. Thanks – SOHO Developer Mar 01 '18 at 19:49
  • @SOHODeveloper, this was definitely true in MVC 3. TBH, the framework has evolved tremendously, and I don't use partials anymore. Not long after this post I moved into using AngularJS and now create dynamic pages. I usually serve a full SPA and my apps have very few views I bother posting. So, as a result, I have no idea if this has changed with MVC 4, 5, or 6. From your response, it seems it may have. I would suggest going with the accepted answer and using JQuery. When I posted the answer, I was answering factually, not suggesting what I thought was best approach. – Dave Alperovich Mar 02 '18 at 09:55
  • Dave, I am trying to implement this in my own application but admittedly I have a low IQ. I need a bit of hand holding and need to understand how to implement this. – Charles Owen Apr 10 '20 at 21:31
3

As normal what I find when looking for things like this is people give too limited information so I will attempt to help here. The key is to set up a div with an ID you can append the return html to. Also when hitting your controller make sure it returns the partial. There are some potential problems with this method but on a good day it should work.

<div id="CategoryList" class="widget">
    @{
        Html.RenderPartial("WidgetCategories.cshtml");
    }
</div>

          function DeleteCategory(CategoryID) {
            $.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
                function (data) {
                    if (data == "No") {
                        alert('The Category has report widgets assigned to it and cannot be deleted.');
                    }
                    else {
                        $('#CategoryList').html(data);
                    }

                }
            );
        }


    [HttpGet("DeleteWidgetCategory")]
    [HttpPost("DeleteWidgetCategory")]
    public IActionResult DeleteWidgetCategory(string CategoryID)
    {
        string Deleted = CategoryModel.DeleteCategory(CategoryID);

        if (Deleted == "Yes")
        {
            return PartialView("WidgetCategories");
        }
        else
        {
            return this.Json("No");
        }
    }
Deathstalker
  • 794
  • 10
  • 8
2

I would use the Ajax Form helper for such scenarios using a partial view and @html.RenderPartial("partialName") partial helpers

Stokes
  • 23
  • 3
1

In your Main View

<div id=SearchResult>
   @Html.Partial("_NameOfPartialView", Model)
</div>

<input type="button" id="btnSubmit" value="Submit">

In your Javascript file

$('#btnSubmit').click(function () {
    GetData(Id);
});

function GetData(Id){
  $.ajax({
     url: "/Home/GetEmployee/",
     type: "get",
     data: { Id:Id },
     success: function (result) {
     $('#SearchResult').html(result);
     }
   });
}

In your Home Controller

public ActionResult GetEmployee(int Id)
{
   var employee= context.Employee.Where(x=> x.EmployeeId == Id)

   return this.PartialView("_NameOfPartialView", employee);
}
Pramesh
  • 1,194
  • 12
  • 16