简体   繁体   中英

ASP.NET MVC ActionLink whith javascript function

I have a list with action links. All links must load a partial view by param in modal popup.

Links:

@model IEnumerable<string>

<ul>
    @foreach (var item in Model)
    {
        <li>
            @Html.ActionLink(item, "MyAction", null, new {code = item}, new {@class = "myclass" })
        </li>
    }
</ul>

MyAction:

public ActionResult MyAction(string code)
{
    // logic
    var model = ...

    return PartialView("_MyPartialView", model);
}

My view with modal popup and javascript function:

<script type="text/javascript">     
$(function() {
    $(function() {
        $('#my-dialog').dialog({
            autoOpen: false,
            width: 400,
            modal: true
        });

        $('.myclass').click(function (e) {
            e.preventDefault();
            $('#my-dialog').load(this.href, function () {
                $(this).dialog('open');
            });
            return false;
        });
    });
</script>    
<div id="my-dialog"></div>

But js function on click actionlink does not work and partial view just load in new page. I try to make break point in this function, but break point does not work, what means that function did not call by click event. Thanks for advice

Try this.......

<script type="text/javascript">     
$(function() {
    $(function() {
        $('#my-dialog').dialog({
            autoOpen: false,
            width: 400,
            modal: true
        });

          $(body).on('click','.myclass',function(e){       
            e.preventDefault();
            $('#my-dialog').load(this.href, function () {
                $(this).dialog('open');
            });
            return false;
        });
    });
</script>    
<div id="my-dialog"></div>

Once your view is rendered the only way to load a partial view is via an Ajax call which returns the partial view to your popup

HTML

@model IEnumerable<string>

<ul>
@foreach (var item in Model)
{
    <li>
       <a onclick="showModal('@item')" class="myclass">item</a>
    </li>
}

<div id="my-dialog"></div>

Jquery

<script type="text/javascript">     
$(function() {
    $('#my-dialog').dialog({
        autoOpen: false,
        width: 400,
        modal: true
    });

 function showModal(code) {
        $.ajax({
            url: "myController/MyAction?code="+code,
            type: 'get',
            success: function (result) {
                $('#my-dialog').html(result);
                $('#my-dialog').dialog('open')
            },
            }
        });
    }
</script>  

Action:

public ActionResult MyAction(string code)
{
// logic
var model = ...

return PartialView("_MyPartialView", model);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM