Update a DIV with a Partial View on Button Click (

2019-07-28 22:22发布

问题:

So I want to do something almost exactly like you find here: http://www.makeitspendit.com/calling-asp-mvc-controllers-from-jquery-ajax/

It will do exactly what I want it to do, but having the same script written out for all 4 buttons is not very DRY. (Well, not DRY at all)

I would like to have one script to call the correct view based on the ID of the button, so that code would only have to be on my page once. I tried passing this.id into the function call, and using concatenation in the "url:" property of the ajax call but that doesn't work.
EXAMPLE:

<div id="projectDiv">

<button onclick="loadProject(this.id)" id="_Project1">Project 1</button>
<button onclick="loadProject(this.id)" id="_Project2">Project 2</button>

<script>    
    function loadProject(projectID) {
          $.ajax({
            url: ("/Projects/Project/"+projectID),
            datatype: "text",
            type: "POST",
            success: function (data) {
              $('#projectDiv').html(data);
            },
          });
        });
</script>

And in the controller:

[HttpPost]
public ActionResult Project(string id)
{
    return View(id);
}

I've searched all over for this and found similar things (but not similar enough to derive what I need) but couldn't find this scenario -- which I would've assumed was common enough to have more information.

The example code illustrates how I would LIKE it to work, but I can't seem to pass the variable into the url property like that. While I am admittedly pretty new to ASP.NET MVC, this seems like it should be pretty basic and yet I've been stuck on this for a minute.

回答1:

I realize this post is over a year old at this point, but I wanted to add a more complete answer based off the comments made on the original question, in case others like me stumble across it.

In my /Views/Shared/ folder I have _YourPartialName.cshtml

In my HomeController.cs I have:

[HttpPost]
public PartialViewResult AddPartialToView(string id)
{
    return PartialView(id);
}

In my MainView.cshtml I have:

...
<div id="placeHolderDiv">          
</div>

<div class="form-group">
    <button class="btn" type="button" onclick="replaceContentsOfDiv(this.id)" id="_YourPartialName">Add A Partial View Above This</button>
</div>
...
<script>
    function replaceContentsOfDiv(partialViewToInsert) {
        $.ajax({
            url: '@Url.Action("AddPartialToView", "Home")',
            data: { id: partialViewToInsert},
            type: "POST",
            success: function(data) {
                $('#placeHolderDiv').html(data);
            }
        });
    }
</script>

This will result in:

<div id="placeHolderDiv">
    <whatever class="you had in your partial">
    </whatever>
</div>



Hope this helps.