如何使用jquery或ajax在c#/asp.net中为MVC项目更新razor局部视图 [英] How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

查看:14
本文介绍了如何使用jquery或ajax在c#/asp.net中为MVC项目更新razor局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVC 部分视图文件中,我构建了一个 Html.TextBox 和两个提交按钮.单击这两个按钮将增加/减少 Html.TextBox 值.Html.TextBox 显示的值将相应更改.但是,一旦我需要根据单击后的新值更新#refTable div.该页面或部分从未更新.代码如下,其中添加了一些注释以供解释.感谢您的帮助.

//******* cshtml 文件 **********//

<input type="submit" value="PrevY" name="chgYr2" id="pY"/>@{var tempItem3 = Model.First();//只给出数据库中的第一个条目,有效.if (ViewData["curSel"] == null){@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());ViewBag.selYear = Convert.ToDateTime(tempItem3.Holiday_date).Year;//只是初始值,有效ViewData["curSel"] = Convert.ToDateTime(tempItem3.Holiday_date).Year;}别的{@Html.TextBox("yearSelect3", ViewData["curSel"].ToString());}}<input type="submit" value="NextY" name="chgYr2" id="nY"/><script type="text/javascript">$(document).ready(function () {$(document).on("click", "#nY", function () {var val = $('#yearSelect3').val();$('#yearSelect3').val((val * 1) + 1);var dataToSend = {id: ((val * 1) + 1)}//添加一些 jquery 或 ajax 代码来更新 #refTable div//ViewBag.selYear 也需要更新为 ((val * 1) + 1)//喜欢:ViewBag.selYear = ((val * 1) + 1);//任何类似的临时变量都可以});});$(document).on("click", "#pY", function () {var val = $('#yearSelect3').val();$('#yearSelect3').val((val * 1) - 1);var dataToSend = {id: ((val * 1) - 1)}});});<span style="float: right"><a href="/">设置 2013 年假日日历</a></span><span id="btnAddHoliday">@Html.ActionLink("添加假期", "创建", null, new { id = "addHilBtn" })</span><div id="refTable"><table class="tblHoliday" style="width: 100%;"><th>假期</th><th>日期</th><th>修改</th><th>删除</th></tr>@foreach(模型中的变量项目){if ( Convert.ToDateTime(item.Holiday_date).Year == ViewBag.selYear)//如果 ViewBag.selYear 是硬编码,这个选择有效"{<tr><td>@Html.DisplayFor(modelItem => item.Holiday_Name)</td><td>@item.Holiday_date.Value.ToString("MM/dd/yyyy")</td><td>@Html.ActionLink("Edit", "Edit", new { })</td><td>@Html.ActionLink("删除", "删除", new { })</td></tr>}}

解决方案

如果您想在不重新加载整个页面的情况下更新页面的一部分,则需要 AJAX.

主 cshtml 视图

<!-- 部分视图内容将插入此处-->

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());<button id="pY">PrevY</button><脚本>$(document).ready(function() {$("#pY").on("click", function() {var val = $('#yearSelect3').val();$.ajax({url: "/假期/日历",类型:获取",数据:{ 年:((val * 1) + 1) }}).done(function(partialViewResult) {$("#refTable").html(partialViewResult);});});});

您需要添加我省略的字段.我使用了 <button> 而不是提交按钮,因为你没有表单(我在你的标记中没有看到一个),你只需要它们来触发客户端上的 javascript一边.

HolidayPartialView 被渲染成 html,jquery done 回调将该 html 片段插入 refTable div.

HolidayController 更新操作

[HttpGet]公共 ActionResult 日历(整数年){var date = new List() {/* 基于年份的值 */};HolidayViewModel 模型 = 新的 HolidayViewModel {日期 = 日期};return PartialView("HolidayPartialView", 模型);}

此控制器操作采用 year 参数并使用强类型视图模型而不是 ViewBag 返回日期列表.

查看模型

公共类HolidayViewModel{IEnumerable日期 { 得到;放;}}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;<table class="tblHoliday">@foreach(Model.Dates 中的变量日期){<tr><td>@date.ToString("MM/dd/yyyy")</td></tr>}

这是插入到您的 div 中的内容.

In a MVC partial view file, I build one Html.TextBox and two submit buttons. These two buttons will increase/decrease the Html.TextBox value once clicked. The Html.TextBox displayed value will change accordingly.However, once I need to update the #refTable div based on the new value after click. The page or section never updated. Codes are below, where some comments are added for explanation purpose. Thanks for your help.

//******* cshtml file **********//

<body>
</body>

<input type="submit" value="PrevY" name="chgYr2" id="pY" />
@{
    var tempItem3 = Model.First(); // just give the first entry from a database, works.
    if (ViewData["curSel"] == null)
    {
    @Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());  
    ViewBag.selYear = Convert.ToDateTime(tempItem3.Holiday_date).Year; // just initial value, works
    ViewData["curSel"] = Convert.ToDateTime(tempItem3.Holiday_date).Year;
    }
    else
    {
    @Html.TextBox("yearSelect3", ViewData["curSel"].ToString());
    } 
}
<input type="submit" value="NextY" name="chgYr2" id="nY" />


<script type="text/javascript">
    $(document).ready(function () {
        $(document).on("click", "#nY", function () {
            var val = $('#yearSelect3').val();
            $('#yearSelect3').val((val * 1) + 1);
            var dataToSend = {
                id: ((val * 1) + 1)
            }
            // add some jquery or ajax codes to update the #refTable div
            // also ViewBag.selYear need to be updated as ((val * 1) + 1)
            // like:   ViewBag.selYear = ((val * 1) + 1);
            // any similar temp variable is fine
        });

        });
        $(document).on("click", "#pY", function () {
            var val = $('#yearSelect3').val();
            $('#yearSelect3').val((val * 1) - 1);
            var dataToSend = {
                id: ((val * 1) - 1)
            }

        });
    });
</script>



<span style="float: right"><a href="/">Set Holiday Calender for 2013</a></span>
<span id="btnAddHoliday">@Html.ActionLink("Add Holiday", "Create", null, new { id = "addHilBtn" })</span>

<div id="refTable">
    <table class="tblHoliday" style="width: 100%;">
            <th>
                Holiday
            </th>
            <th>
                Dates
            </th>
            <th>Modify</th>
            <th>Delete</th>
        </tr>

        @foreach (var item in Model)
        {

            if (    Convert.ToDateTime(item.Holiday_date).Year == ViewBag.selYear)
            // if the ViewBag.selYear is hard code, this selection "works"
            {
            <tr>                
                <td>
                    @Html.DisplayFor(modelItem => item.Holiday_Name)
                </td>               
                <td>
                    @item.Holiday_date.Value.ToString("MM/dd/yyyy")
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new {  })
                </td>
                <td>
                    @Html.ActionLink("Delete", "Delete", new {  })
                </td>
            </tr>
            }
        }

    </table>
</div>

解决方案

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

这篇关于如何使用jquery或ajax在c#/asp.net中为MVC项目更新razor局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆