MVC: Can't make fancybox work

2019-09-04 10:24发布

问题:

I am trying to update an existing application and wants to display modal using fancybox. On other functionalities, I was able to display the fancybox but for some reason cannot do it on a particular view.

Here is my main view declaration:

@Html.ActionLink(Strings.Link_ViewFullList, "OrganisationFullList", new { id = 1 }, new { @class = "fancybox fancybox.ajax" })

Then here is my "organisationFullList" cshtml file.

@model ProjectOrganisationModel
@{
    ViewBag.Title = Strings.PageTitles_Organisations;
}
<div class="row">
    <div class="col-lg-10">
                @if (Model.Organisation != null && Model.Organisation.Any())
                {
                    <ul class="list-unstyled">
                        @foreach (var organisation in Model.Organisation)
                        {
                            <li>
                                @Html.RadioButton("organisationList", organisation.Name)
                                @Html.Label(organisation.Name, new { style = "font-weight: normal" })
                            </li>
                        }
                    </ul>
                }
    </div>
</div>

Here is my controller code:

    public ActionResult OrganisationFullList(int id)
    {
        var organisationList = new ProjectOrganisationModel();
        organisationList.Organisation = GetOrganisations();
        return View(organisationList);
    }

When I click on the link, it displays a new screen instead of the modal. It redirects to this URl: https://localhost:44300/project/1/organisationfulllist

回答1:

@Html.ActionLink causes you to redirect to another page.

Rather than using @Html.ActionLink use @Ajax.ActionLink

@Ajax.ActionLink(
    "View Full List Ajax",
    "OrganisationFullList", //Action
    "YourController", //Controller
    new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "showFancyBox" //call back
    }
)

Call back function:

function showFancyBox(data) {
    $.fancybox.open({ "content": data });
}

Dont forget to include jquery.unobtrusive-ajax.min.js you need it to use @Ajax helpers

<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>