Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC3 - Using partial view to append new HTML elements to page

I am currently using an Ajax call on my ASP MVC3 view to append a new list item to the page. The view makes the Ajax call, which calls a controller ViewResult action, which returns the partial view. The Ajax is then set to call the .append(html) method on the <div> element the call originated from.

The problem is that instead of appending the new row, the entire view goes away and only the partial is displayed.

Here is the code in the view. This view uses a view model with a list object of a separate model. This portion of the code calls the partial view to display each of the items in the list object.

@model Monet.ViewModel.BankListViewModel
@using (Html.BeginForm())
{
    <fieldset>
        <legend>Stat(s) Fixed</legend>
        <table>
        <th>State Code</th>
        <th>Agent ID</th>
        <th></th>
            <div class="fixedRows">
                @foreach(var item in Model.Fixed)
                {
                    if (!String.IsNullOrWhiteSpace(item.AgentId))
                    {

                            @Html.Partial("FixedPartialView", item) 

                    }      
                }
            </div>
        </table>
        <br />
        @Html.ActionLink("Add another", "BlankFixedRow", null, new { id = "addFixed"})
    </fieldset>
}

Here is the addFixed Ajax call

$("#addFixed").click(function () {
    $.ajax({
        url: this.href,
        cache: false,
        success: function (html) { $("#fixedRows").append(html); }
    });
    return false;
});

and this is the ViewResult controller action that the Ajax calls

    public ViewResult BlankFixedRow()
    {
        SelectList tmpList = new SelectList(new[] { "AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NA", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "US", "VT", "VI", "VA", "WA", "WV", "WI", "WY" });
        ViewBag.StateCodeList = tmpList;

        return View("FixedPartialView", new BankListAgentId());
    }

Finally, this is the partial view.

@model Monet.Models.BankListAgentId


@using (Html.BeginCollectionItem("Fixed"))
{
    <tr id="[email protected]">
        <td>
            @Html.DropDownListFor(model => model.StateCode,
                (SelectList)ViewBag.StateCodeList, Model.StateCode)
        </td>
        <td>
            @Html.EditorFor(model => model.AgentId)
            @Html.ValidationMessageFor(model => model.AgentId)
        </td>
        <td>
        <a href="#" onclick="$('#[email protected]').parent().remove();" style="float:right;">Delete</a></td>
    </tr>
}

When the Add another link is selected the page goes from looking like this

enter image description here

to this

enter image description here

Per comments below here is the HTML for the page:

<input type="hidden" name="Fixed.index" autocomplete="off" value="6dd1b028-14f7-4400-95d1-a803c2521b68" />
        <tr id="item-">
            <td>
                <select id="Fixed_6dd1b028-14f7-4400-95d1-a803c2521b68__StateCode" name="Fixed[6dd1b028-14f7-4400-95d1-a803c2521b68].StateCode"><option>AL</option>
<option>AK</option>
<option>AS</option>
<option>AZ</option>

.
.
. <-removed list of all 50 states for clarity
</select>
            </td>
            <td>
                <input class="text-box single-line" id="Fixed_6dd1b028-14f7-4400-95d1-a803c2521b68__AgentId" name="Fixed[6dd1b028-14f7-4400-95d1-a803c2521b68].AgentId" type="text" value="" />

            </td>
            <td>
                <a href="#" class="deleteRow">delete</a>
            </td>

        </tr>
                    </section>

EDIT

After reading the comments below I changed the table tag to <table id="fixedRows">, however, this returned the same result. I then changed the success attribute of the Ajax call to include some basic HTML like so

success: function (html) { $("#fixedRows").append("<tr><td>New</td></tr>"); }

but again, got the same result. After setting a breakpoint both in Visual Studio and Chrome's debugger, I was able to see that the Ajax is never being called. Instead the call to the controller action is made, and the partial view is loaded on it's own, instead of being appended to <table id="fixedRows">.

Still working of getting around this, however, if anyone has any ideas. Thx!

like image 849
NealR Avatar asked Apr 03 '13 18:04

NealR


People also ask

How do I use Rendersection in partial view?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

What is HTML partial in MVC?

A partial view is a Razor markup file ( .cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.


1 Answers

So the reason this was happening wound up being pretty simple. Due to the ActionLink that was being used, the controller action would fire before the jQuery. This was causing the partial view to wipe out the entire Edit view. By binding the jQuery to a hyperlink within a $(document).ready block, the jQuery functioned like normal. Below is the tag and the updated jQuery

<a href="#" class="addFixed">Add Another</a>

jQuery:

$(document).ready(function () {

    $(".addFixed").click(function () {
        //alert('test');
        event.preventDefault();        
        $.ajax({
            url: '@Url.Action("BlankFixedRow", "BankListMaster")',
            cache: false,
            success: function (html) { $("#fixedRows").append(html); }
        });
    });

    $("#addVariable").click(function () {
        event.preventDefault();
        $.ajax({
            url: '@Url.Action("BlankFixedRow", "BankListMaster")',
            cache: false,
            success: function (html) { $("#variableRows").append(html); }
        });
    });

});
like image 83
NealR Avatar answered Oct 13 '22 00:10

NealR