MVC5:点击按钮点击部分视图?

时间:2015-03-02 15:35:08

标签: javascript jquery asp.net-mvc razor partial-views

我的VerifyAsset/Index视图目前定义如下:

@using GridMvc.Html
@using System.Collections.Generic
@model List<InventoryTracker.Models.INV_Assets>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Verify Assets</h3>

<div class="mainAssetBtns">
    @Html.DropDownList("NumberValueSelection", Enumerable.Range(1, 31).Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString() }))
    @Html.DropDownList("intervalList")
    <a href="#" class="btn btn-info btn-sm noDecoration" onclick="newCutoffDate()"><span class="glyphicon glyphicon-refresh"> REFRESH</span></a>
    @*<a href="/INV_Assets/Create" class="btn btn-success btn-sm noDecoration"><span class="glyphicon glyphicon-plus"></span> Create Asset</a>
    <a href="/Home/Index" class="btn btn-info btm-sm noDecoration"><span class="glyphicon glyphicon-filter"></span> Clear All Filters</a>*@
</div>

@* prism - admin/usermanagement/index - mvcgrid example *@
<div class="assetList">

    @*Images in Columns: https://gridmvc.codeplex.com/discussions/440977*@
    @try
    {
        @Html.Grid(Model).Columns(columns =>
        {
            columns.Add().Encoded(false).Sanitized(false).SetWidth(30).RenderValueAs(o => @Html.CheckBox("checked", false));
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => @<a href="#" class="btn btn-default btn-sm noDecoration verifyBtn" onclick="verifyAsset(@o.Id)"><span class="glyphicon glyphicon-ok"></span> @*View*@</a>).SetWidth(15);
            @*columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => @<a href="/INV_Assets/Details/@o.Id" class="btn btn-default btn-sm noDecoration"><span class="glyphicon glyphicon-eye-open"></span> @*View*</a>).SetWidth(15);*@
            columns.Add(o => o.Status.status_description).Titled("Status").RenderValueAs(o => o.Status.status_description).Sanitized(false).Encoded(false).Sortable(true).Filterable(true).SetWidth(20);
            columns.Add(o => o.Location.location_dept).Titled("Dept").RenderValueAs(o => o.Location.location_dept).SetWidth(20);
            columns.Add(o => o.Location.location_room).Titled("Room").RenderValueAs(o => o.Location.location_room).SetWidth(20);
            columns.Add(o => o.owner).Titled("Owner").RenderValueAs(o => o.owner).SetWidth(20);
            columns.Add(o => o.Type.type_description).Titled("Type").RenderValueAs(o => o.Type.type_description).SetWidth(20);
            columns.Add(o => o.Manufacturer.manufacturer_description).Titled("Manufacturer").RenderValueAs(o => o.Manufacturer.manufacturer_description).SetWidth(20);
            columns.Add(o => o.Model.model_description).Titled("Model").RenderValueAs(o => o.Model.model_description).SetWidth(20);
            columns.Add(o => o.Vendor.vendor_name).Titled("Vendor").RenderValueAs(o => o.Vendor.vendor_name).SetWidth(20);
            columns.Add(o => o.description).Titled("Desc").RenderValueAs(o => o.description).SetWidth(20);
            columns.Add(o => o.asset_tag_number).Titled("Asset Tag #").RenderValueAs(o => o.asset_tag_number).SetWidth(20);
            columns.Add(o => o.serial_number).Titled("Serial #").RenderValueAs(o => o.serial_number).SetWidth(20);
            columns.Add(o => o.ip_address).Titled("IP Addr").RenderValueAs(o => o.ip_address).SetWidth(20);
            columns.Add(o => o.mac_address).Titled("Mac Addr").RenderValueAs(o => o.mac_address).SetWidth(20);
            columns.Add(o => o.po_number).Titled("PO #").RenderValueAs(o => o.po_number).SetWidth(20);
            columns.Add(o => o.invoice_number).Titled("Inv. #").RenderValueAs(o => Convert.ToString(o.invoice_number)).SetWidth(20);
            columns.Add(o => o.cost).Titled("Cost").RenderValueAs(o => "$" + Convert.ToString(o.cost)).SetWidth(20);
            columns.Add(o => o.note).Titled("Note").RenderValueAs(o => o.note).SetWidth(20);
            columns.Add(o => o.acquired_date).Titled("Acq. Date").RenderValueAs(o => Convert.ToString(o.acquired_date)).SetWidth(20);
            columns.Add(o => o.disposed_date).Titled("Disp. Date").RenderValueAs(o => Convert.ToString(o.disposed_date)).SetWidth(20);
            columns.Add(o => o.verified_date).Titled("Ver. Date").RenderValueAs(o => Convert.ToString(o.verified_date)).SetWidth(20);
            columns.Add(o => o.created_date).Titled("Crtd. Date").RenderValueAs(o => Convert.ToString(o.created_date)).SetWidth(20);
            columns.Add(o => o.created_by).Titled("By").RenderValueAs(o => o.created_by).SetWidth(20);
            columns.Add(o => o.modified_date).Titled("Mod. Date").RenderValueAs(o => Convert.ToString(o.modified_date)).SetWidth(20);
            columns.Add(o => o.modified_by).Titled("By").RenderValueAs(o => o.modified_by).SetWidth(20);
        }).WithPaging(100).Sortable().Filterable().WithMultipleFilters();
    }
    catch (NullReferenceException ex)
    {
        return;
    }
</div>

我正在尝试将<div class="assetList">设置为部分视图,用户可以根据下拉选项刷新并点击[REFRESH]按钮。

我创建了一个名为_VerificationPartial的部分视图:

@using GridMvc.Html
@using System.Collections.Generic
@model List<InventoryTracker.Models.INV_Assets>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Verify Assets</h3>

<div class="mainAssetBtns">
    @Html.DropDownList("NumberValueSelection", Enumerable.Range(1, 31).Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString() }))
    @Html.DropDownList("intervalList")
    <a href="#" class="btn btn-info btn-sm noDecoration" onclick="newCutoffDate()"><span class="glyphicon glyphicon-refresh"> REFRESH</span></a>
    @*<a href="/INV_Assets/Create" class="btn btn-success btn-sm noDecoration"><span class="glyphicon glyphicon-plus"></span> Create Asset</a>
    <a href="/Home/Index" class="btn btn-info btm-sm noDecoration"><span class="glyphicon glyphicon-filter"></span> Clear All Filters</a>*@
</div>

@* prism - admin/usermanagement/index - mvcgrid example *@
<div class="assetList">

    @*Images in Columns: https://gridmvc.codeplex.com/discussions/440977*@
    @try
    {
        @Html.Grid(Model).Columns(columns =>
        {
            columns.Add().Encoded(false).Sanitized(false).SetWidth(30).RenderValueAs(o => @Html.CheckBox("checked", false));
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => @<a href="#" class="btn btn-default btn-sm noDecoration verifyBtn" onclick="verifyAsset(@o.Id)"><span class="glyphicon glyphicon-ok"></span> @*View*@</a>).SetWidth(15);
            @*columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => @<a href="/INV_Assets/Details/@o.Id" class="btn btn-default btn-sm noDecoration"><span class="glyphicon glyphicon-eye-open"></span> @*View*</a>).SetWidth(15);*@
            columns.Add(o => o.Status.status_description).Titled("Status").RenderValueAs(o => o.Status.status_description).Sanitized(false).Encoded(false).Sortable(true).Filterable(true).SetWidth(20);
            columns.Add(o => o.Location.location_dept).Titled("Dept").RenderValueAs(o => o.Location.location_dept).SetWidth(20);
            columns.Add(o => o.Location.location_room).Titled("Room").RenderValueAs(o => o.Location.location_room).SetWidth(20);
            columns.Add(o => o.owner).Titled("Owner").RenderValueAs(o => o.owner).SetWidth(20);
            columns.Add(o => o.Type.type_description).Titled("Type").RenderValueAs(o => o.Type.type_description).SetWidth(20);
            columns.Add(o => o.Manufacturer.manufacturer_description).Titled("Manufacturer").RenderValueAs(o => o.Manufacturer.manufacturer_description).SetWidth(20);
            columns.Add(o => o.Model.model_description).Titled("Model").RenderValueAs(o => o.Model.model_description).SetWidth(20);
            columns.Add(o => o.Vendor.vendor_name).Titled("Vendor").RenderValueAs(o => o.Vendor.vendor_name).SetWidth(20);
            columns.Add(o => o.description).Titled("Desc").RenderValueAs(o => o.description).SetWidth(20);
            columns.Add(o => o.asset_tag_number).Titled("Asset Tag #").RenderValueAs(o => o.asset_tag_number).SetWidth(20);
            columns.Add(o => o.serial_number).Titled("Serial #").RenderValueAs(o => o.serial_number).SetWidth(20);
            columns.Add(o => o.ip_address).Titled("IP Addr").RenderValueAs(o => o.ip_address).SetWidth(20);
            columns.Add(o => o.mac_address).Titled("Mac Addr").RenderValueAs(o => o.mac_address).SetWidth(20);
            columns.Add(o => o.po_number).Titled("PO #").RenderValueAs(o => o.po_number).SetWidth(20);
            columns.Add(o => o.invoice_number).Titled("Inv. #").RenderValueAs(o => Convert.ToString(o.invoice_number)).SetWidth(20);
            columns.Add(o => o.cost).Titled("Cost").RenderValueAs(o => "$" + Convert.ToString(o.cost)).SetWidth(20);
            columns.Add(o => o.note).Titled("Note").RenderValueAs(o => o.note).SetWidth(20);
            columns.Add(o => o.acquired_date).Titled("Acq. Date").RenderValueAs(o => Convert.ToString(o.acquired_date)).SetWidth(20);
            columns.Add(o => o.disposed_date).Titled("Disp. Date").RenderValueAs(o => Convert.ToString(o.disposed_date)).SetWidth(20);
            columns.Add(o => o.verified_date).Titled("Ver. Date").RenderValueAs(o => Convert.ToString(o.verified_date)).SetWidth(20);
            columns.Add(o => o.created_date).Titled("Crtd. Date").RenderValueAs(o => Convert.ToString(o.created_date)).SetWidth(20);
            columns.Add(o => o.created_by).Titled("By").RenderValueAs(o => o.created_by).SetWidth(20);
            columns.Add(o => o.modified_date).Titled("Mod. Date").RenderValueAs(o => Convert.ToString(o.modified_date)).SetWidth(20);
            columns.Add(o => o.modified_by).Titled("By").RenderValueAs(o => o.modified_by).SetWidth(20);
        }).WithPaging(100).Sortable().Filterable().WithMultipleFilters();
    }
    catch (NullReferenceException ex)
    {
        return;
    }
</div>

我似乎无法弄清楚如何使用@Html.RenderPartial来呈现我的观点,因为我不清楚如何提供Model参数?

@Html.RenderPartial("~/Views/Shared/_VerificationPartial.cshtml")目前产生"cannot implicitly convert type 'void' to 'object'

我的VerifyAsset/Index控制器操作定义如下:

    public async Task<ActionResult> Index()
    {
        List<SelectListItem> intervalList = new List<SelectListItem>();
        intervalList.Add(new SelectListItem { Text = "Month", Value = "Month" });
        intervalList.Add(new SelectListItem { Text = "Day", Value = "Day" });
        intervalList.Add(new SelectListItem { Text = "Year", Value = "Year" });
        var cutoffDate = DateTime.Now.AddMonths(-3);
        var iNV_Assets = db.INV_Assets.Where(i => i.verified_date < cutoffDate).Include(i => i.Location).Include(i => i.Manufacturer).Include(i => i.Model).Include(i => i.Status).Include(i => i.Type).Include(i => i.Vendor);
        ViewBag.intervalList = intervalList;
        return View(await iNV_Assets.ToListAsync());
        //return PartialView("~/Views/Shared/_VerificationPartial.cshtml", await iNV_Assets.ToListAsync());
    }

这是我在我的视图中使用的脚本,我试图调用我的控制器操作来刷新局部视图 - 注意:我的参数值已正确填写,但是尝试在控制器上找到Action时出现404错误?:

    function newCutoffDate() {
        var _value = document.getElementById("NumberValueSelection").value;
        var _interval = document.getElementById("intervalList").value;
        var data = { value: _value, interval: _interval };
        var url = '~/VerifyAssets/NewCutoffDateInterval'
        $.get(url, { value: _value, interval: _interval })
        .done(function (response) {
            $("#assetList").html(response);
        });
        //window.location.href = url;
        @*$.ajax({
            type: "POST",
            dataType: "JSON",
            url: '@Url.Action("NewCutoffDateInterval", "VerifyAssets")',
            data: data,
            success: function (resp) {
                alert("Sucess! Value: " + resp.value + " | Interval: " + resp.interval);
            },
            error: function (resp) {
                alert("Error! Value: " + resp.value + " | Interval: " + resp.interval);
            }
        })*@
    }

VerifyAssets / NewCutoffDateInterval

    [HttpGet]
    public async Task<ActionResult> NewCutoffDateInterval(int value, string interval)
    {
        var cutoffDate = DateTime.Now.AddMonths(-3);
        if (interval == "Month")
        {
            cutoffDate = DateTime.Now.AddMonths(-value);
        }
        else
        {
            if (interval == "Day")
            {
                cutoffDate = DateTime.Now.AddDays(-value);
            }
            else
            {
                if (interval == "Year")
                {
                    cutoffDate = DateTime.Now.AddYears(-value);
                }
            }
        }

        var iNV_Assets = db.INV_Assets.Where(i => i.verified_date < cutoffDate).Include(i => i.Location).Include(i => i.Manufacturer).Include(i => i.Model).Include(i => i.Status).Include(i => i.Type).Include(i => i.Vendor);

        if (Request.IsAjaxRequest())
        {
            return PartialView("~/Views/Shared/_VerificationPartial.cshtml", await iNV_Assets.ToListAsync());
        }
        else
        {
            return PartialView("~/Views/Shared/_VerificationPartial.cshtml", await iNV_Assets.ToListAsync());
        }

    }

有经验的人可以帮忙解决这个问题吗?


修改

谢谢大家的建议!我的部分视图现在在视图上呈现,脚本现在成功调用我的操作方法。

当我的部分视图刷新时,似乎有一个小问题。

我的 VerifyAssets / Index 视图现在是:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Verify Assets</h3>

<div class="mainAssetBtns">
    @Html.DropDownList("NumberValueSelection", Enumerable.Range(1, 31).Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString() }))
    @Html.DropDownList("intervalList")
    <a href="#" class="btn btn-info btn-sm noDecoration" onclick="newCutoffDate()"><span class="glyphicon glyphicon-refresh"> REFRESH</span></a>
    @*<a href="/INV_Assets/Create" class="btn btn-success btn-sm noDecoration"><span class="glyphicon glyphicon-plus"></span> Create Asset</a>
    <a href="/Home/Index" class="btn btn-info btm-sm noDecoration"><span class="glyphicon glyphicon-filter"></span> Clear All Filters</a>*@
</div>

@Html.Partial("~/Views/Shared/_VerificationPartial.cshtml")

@section Scripts {
        function newCutoffDate() {
            var _value = document.getElementById("NumberValueSelection").value;
            var _interval = document.getElementById("intervalList").value;
            var data = { value: _value, interval: _interval };
            //var url = '~/VerifyAssets/NewCutoffDateInterval'
            var url = '@Url.Action("NewCutoffDateInterval", "VerifyAssets")';
            $.get(url, { value: _value, interval: _interval })
            .done(function (response) {
                alert("Made it here!");
                $(".assetList").html(response);
            });
            //window.location.href = url;
            @*$.ajax({
                type: "POST",
                dataType: "JSON",
                url: '@Url.Action("NewCutoffDateInterval", "VerifyAssets")',
                data: data,
                success: function (resp) {
                    alert("Sucess! Value: " + resp.value + " | Interval: " + resp.interval);
                },
                error: function (resp) {
                    alert("Error! Value: " + resp.value + " | Interval: " + resp.interval);
                }
            })*@
        }
    </script>
}

这是我对加载部分视图的内容:

OnLoad

如果我将间隔更改为5 - Days,则这是内容:

AfterRefresh

我的<div class="assetList">刷新似乎在第一个<div class="assetList">内添加了{{1}}。我怎样才能简单地替换第一个而不是插入一个子div?

1 个答案:

答案 0 :(得分:2)

为了更容易,为什么不想在刷新它时尝试通过AJAX调用将部分视图作为文本返回到页面?

例如,在控制器中,您可以使用一个将返回局部视图的操作方法:

public async Task<ActionResult> GetFoo()
{
    return PartialView("~/Views/Shared/_VerificationPartial.cshtml", await iNV_Assets.ToListAsync());
}

然后你会让JavaScript进行$.get()调用以刷新部分所在的视图部分:

$.get("/Home/GetFoo")
.then(function (response) {
    // response will be the HTML of the partial view.
    // e.g. $("#partialviewhost).html(response);
});

所以这几乎就是你已经完成的事情,但是可以生成局部视图HTML以进行刷新。

我希望我能正确理解你的问题。