在项目点击上渲染视图模型

时间:2012-10-25 15:01:41

标签: javascript jquery asp.net-mvc view render

情况如下:我有一个Product模型,它有许多属性,一个是Photo个对象列表,每个Photo对象都有一个ID和一个Name。有一个Carousel View,其模型列表为Photos。在Product视图中,我有类似的内容:

@if (Model.Photos.Count > 0)
{
    ....
    <a href="javascript:jsFunction()".......

在javascript中,jsFunction看起来像这样:

function jsFunction()
{
  alert('@Html.Action("GetPhotosCarousel", Model.Photos)');
} 

并且Controller函数返回部分视图_PhotosCarousel

现在,@Html.Action在渲染主视图时执行的问题 NOT ON CLICK

如何在点击时呈现视图PhotosCarousel,而不是在显示页面时?

2 个答案:

答案 0 :(得分:1)

我建议从jsFunction删除对href的实际调用,然后使用jQuery处理它。

<a href="#" id="photoCarouselHref">Click Me</a>

$(document).ready(function(){
    $("#photoCarouselHref").click(function(){
        $.ajax({
            url: '@Url.Action("GetPhotosCarousel"),
            //other ajax settings here
        });
    });
});

jQuery ajax文档here

答案 1 :(得分:0)

你可以试试这个:

代码已准备好拥有多个锚元素:

HTML:

<div class="container">

    <a href="@Url.Action("GetPhotosCarousel")" 
        data-id="@Model.Id" 
        data-name="@Model.Name" 
        class="call-get-photos-carousel">click</a>

    <div class="result"></div>

</div>

JS:

$(document).ready(function(){

    $('.call-get-photos-carousel').bind('click', function(event) {

        var 
            _this = this, 
            data = {'Id': $(this).data('id'), 'Name': $(this).data('name')};

        $.get($(this).attr('href'), data,  function(html) {
            $(_this).siblings('.result').html(html);
        });

        return false;
    });
});

但是如果你只有一个锚元素,你可以在元素中以ID的方式工作:

HTML:

<div>

    <a href="@Url.Action("GetPhotosCarousel")" 
        data-id="@Model.Id" 
        data-name="@Model.Name" 
        id="call-get-photos-carousel">click</a>

    <div id="result"></div>

</div>

JS:

$(document).ready(function(){

    $('#call-get-photos-carousel').bind('click', function(event) {

        var 
            _this = this, 
            data = {'Id': $(this).data('id'), 'Name': $(this).data('name')};

        $.get($(this).attr('href'), data,  function(html) {
            $('#result').html(html);
        });

        return false;
    });
});

在这两种情况下,操作都会发送到IdName的值。