如何使用jquery或ajax在c#/asp.net中更新MVC项目的razor部分视图

时间:2021-12-22 01:40:11

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.

在MVC部分视图文件中,我构建了一个Html。文本框和两个提交按钮。这两个按钮将增加/减少Html。点击文本框值一次。Html。文本框显示的值将相应地改变。但是,一旦我需要基于单击后的新值更新#refTable div。页面或部分从未更新过。下面是代码,其中添加了一些注释用于解释目的。谢谢你的帮助。

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

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

<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>

3 个解决方案

#1


63  

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

如果希望更新页面的一部分而不重新加载整个页面,则需要使用AJAX。

main cshtml view

主cshtml视图

<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.

度假部分视图呈现为html, jquery完成回调将该html片段插入到refTable div中。

HolidayController Update action

HolidayController更新动作

[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.

这个控制器动作接受year参数,并使用强类型的视图模型而不是ViewBag返回日期列表。

view model

视图模型

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

HolidayPartialView.csthml

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.

这是插入到div中的东西。

#2


2  

The main concept of partial view is returning the HTML code rather than going to the partial view it self.

分部视图的主要概念是返回HTML代码,而不是返回它自己的分部视图。

[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 action return the HTML code of the partial view ("HolidayPartialView").

此操作返回部分视图的HTML代码(“holiday daypartialview”)。

To refresh partial view replace the existing item with the new filtered item using the jQuery below.

要刷新部分视图,请使用下面的jQuery将现有项替换为新的过滤项。

$.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });

#3


0  

You can also use Url.Action for the path instead like so:

您还可以使用Url。相反,路径的作用是:

$.ajax({
        url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",                
        type: "GET",           
        success: function (partialViewResult) {            
            $("#refTable").html(partialViewResult);
        }
    });

#1


63  

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

如果希望更新页面的一部分而不重新加载整个页面,则需要使用AJAX。

main cshtml view

主cshtml视图

<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.

度假部分视图呈现为html, jquery完成回调将该html片段插入到refTable div中。

HolidayController Update action

HolidayController更新动作

[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.

这个控制器动作接受year参数,并使用强类型的视图模型而不是ViewBag返回日期列表。

view model

视图模型

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

HolidayPartialView.csthml

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.

这是插入到div中的东西。

#2


2  

The main concept of partial view is returning the HTML code rather than going to the partial view it self.

分部视图的主要概念是返回HTML代码,而不是返回它自己的分部视图。

[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 action return the HTML code of the partial view ("HolidayPartialView").

此操作返回部分视图的HTML代码(“holiday daypartialview”)。

To refresh partial view replace the existing item with the new filtered item using the jQuery below.

要刷新部分视图,请使用下面的jQuery将现有项替换为新的过滤项。

$.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });

#3


0  

You can also use Url.Action for the path instead like so:

您还可以使用Url。相反,路径的作用是:

$.ajax({
        url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",                
        type: "GET",           
        success: function (partialViewResult) {            
            $("#refTable").html(partialViewResult);
        }
    });