如何使用jQuery或AJAX更新C#​​/ asp.net剃刀局部视图一个MVC项目 [英] How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

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

问题描述

在一个MVC局部视图文件,我构建您只需Html.TextBox和两个提交按钮。这两个按钮将增加/减少一次点击Html.TextBox值。该Html.TextBox显示值会发生变化accordingly.However,一旦我需要根据点击后的新值来更新#refTable股利。页面或部分永远不会更新。 codeS低于,其中一些意见是为解释的目的补充说。感谢您的帮助。

// * 的**的 * 的***的 CSHTML文件的 的**的 * 的**的 * 的**** //

 <身体GT;
< /身体GT;<输入类型=提交值=preVYNAME =chgYr2ID =PY/>
@ {
    变种tempItem3 = Model.First(); //只是给从数据库中的第一项,有效。
    如果(计算机[curSel] == NULL)
    {
    @ Html.TextBox(yearSelect3,Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
    ViewBag.selYear = Convert.ToDateTime(tempItem3.Holiday_date).Year; //只是初值,作品
    计算机[curSel] = Convert.ToDateTime(tempItem3.Holiday_date).Year;
    }
    其他
    {
    @ Html.TextBox(yearSelect3计算机[curSel]的ToString());
    }
}
<输入类型=提交值=NextYNAME =chgYr2ID =NY/>
<脚本类型=文/ JavaScript的>
    $(文件)。就绪(函数(){
        $(文件)。在(点击,#nY功能(){
            。VAR VAL = $('#yearSelect3)VAL();
            $('#yearSelect3')VAL((VAL * 1)+ 1);
            VAR dataToSend = {
                ID:((VAL * 1)+1)
            }
            //添加一些jQuery或AJAX codeS更新#refTable DIV
            //也ViewBag.selYear需要被更新为((VAL * 1)+1)
            //像:ViewBag.selYear =((VAL * 1)+ 1);
            //任何类似的临时变量是罚款
        });        });
        $(文件)。在(点击,#pY功能(){
            。VAR VAL = $('#yearSelect3)VAL();
            $('#yearSelect3')VAL((VAL * 1) - 1);
            VAR dataToSend = {
                ID:((VAL * 1) - 1)
            }        });
    });
< / SCRIPT><跨度风格=浮动:权利>< A HREF =/>设置假期日历2013年< / A>< / SPAN>
<跨度ID =btnAddHoliday> @ Html.ActionLink(添加假日,创建,空,新的{ID =addHilBtn})LT; / SPAN>< D​​IV ID =表reftable>
    <表类=tblHoliday的风格=宽度:100%;>
            <第i个
                假日
            < /第i
            <第i个
                日期
            < /第i
            <第i修改< /第i
            <第i删除< /第i
        < / TR>        @foreach(以型号VAR项)
        {            如果(Convert.ToDateTime(item.Holiday_date).Year == ViewBag.selYear)
            //如果ViewBag.selYear很难code,本次评选作品
            {
            &所述; TR>
                &所述; TD>
                    @ Html.DisplayFor(modelItem => item.Holiday_Name)
                < / TD>
                &所述; TD>
                    @ item.Holiday_date.Value.ToString(MM / DD / YYYY)
                < / TD>
                &所述; TD>
                    @ Html.ActionLink(编辑,编辑,新{})
                < / TD>
                &所述; TD>
                    @ Html.ActionLink(删除,删除,新{})
                < / TD>
            < / TR>
            }
        }    < /表>
< / DIV>


解决方案

如果您想在不重新加载整个页面来更新页面的一部分你需要AJAX。

主要CSHTML视图

 < D​​IV ID =表reftable>
     <! - 局部视图的内容将在这里插入 - >
< / DIV>@ Html.TextBox(yearSelect3,Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<按钮ID =PY> preVY< /按钮><脚本>
    $(文件)。就绪(函数(){
        $(#PY)。在(点击,函数(){
            。VAR VAL = $('#yearSelect3)VAL();
            $阿贾克斯({
                网址:/度假/日历,
                键入:GET,
                数据:{年:((VAL * 1)+1)}
            })
            .done(功能(partialViewResult){
                $(#表reftable)HTML(partialViewResult)。
            });
        });
    });
< / SCRIPT>

您需要添加我省略的字段。我已经使用了<按钮> 而不是提交按钮,因为你没有一个窗体(我没有看到一个在你的标记),你只需要他们触发客户端的JavaScript。

HolidayPartialView 被渲染成HTML和jQuery的完成回调会插入HTML片段插入在表reftable DIV。

HolidayController更新动作

  [HTTPGET]
公众的ActionResult日历(INT年)
{
    VAR日期=新的List<&日期时间GT;(){/ *值的基础上一年* /};
    HolidayViewModel模式=新HolidayViewModel {
        日期=日期
    };
    返回PartialView(HolidayPartialView模型);
}

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

视图模型

 公共类HolidayViewModel
{
    IEnumerable的<&日期时间GT;日期{搞定;组; }
}

HolidayPartialView.csthml

  @model Your.Namespace.HolidayViewModel;<表类=tblHoliday>
    @foreach(在Model.Dates VAR日)
    {
        < 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项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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