提交点击后仅更新(刷新)PartialView [英] Only update (refresh) PartialView after submit click

查看:122
本文介绍了提交点击后仅更新(刷新)PartialView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击输入type ="submit" 按钮后,我只能更新部分视图的内容.我只希望刷新部分视图并用更新的模型(控制器代码)填充它,而不刷新整个页面.但是目前,在以下情况下,我只能查看更新后的模型属性:

I am having trouble only updating the contents of my partial view after clicking a input type="submit" button. I wish to only refresh the partial view and fill it with the updated model (controller code), not refresh the full page. However at the moment I've only been able to view my updated model property in these situations:

  1. 提交后刷新整个页面(通过在控制器中返回View())图像
  2. 提交后仅显示Partial视图(通过在控制器中返回PartialView())图像2

在我看来,JQuery调用未正确实现,它是在调试模式下触发的.我在_Layout.cshtml页面中加载/渲染所有Javascript文件. 另外请注意:我只知道启用#btn-plus,我知道这一点. (如果需要的话,我在底部添加了2张屏幕截图以进行说明)

It seems to me that the JQuery call isn't implemented correctly, it is triggered in debug mode. I load/render all Javascript files in the _Layout.cshtml page. Also note: I've only yet tried to enable the #btn-plus, I am aware of this. (I've added 2 screenshots at the bottom for clarification if needed)

LoadPartialCalc.js

$("btn-plus").on("click", function () {
    $.ajax({
        url: "/Home/CalculationValidation",
        type: "POST",
        success: function (result) {
            $('#dvCalculationResult').html(result);
        }
    })
});

CalculationValidation.cshtml

@using MVCPluginTest.Models
@model MVCPluginTest.Models.CalculatorModel

@{
    ViewBag.Title = "Validation master Page";
}


<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Validation</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
</head>
<body>
    <div id="containter">
        <h2>Validation</h2>
        @using (Html.BeginForm("#ValidationForm"))
        {
            @Html.ValidationSummary(true)
            <fieldset>
                <p>@Html.LabelFor(model => model.Number1)</p>
                <p>@Html.EditorFor(model => model.Number1) @Html.ValidationMessageFor(model => model.Number1)</p>

                <p>@Html.LabelFor(model => model.Number2)</p>
                <p>@Html.EditorFor(model => model.Number2) @Html.ValidationMessageFor(model => model.Number2)</p>

                <p><input type="submit" value="+" name="operation" id="btn-plus"/></p>
                <p><input type="submit" value="-" name="operation" id="btn-minus"/></p>
                <p><input type="submit" value="*" name="operation" id="btn-multiply"/></p>
                <p><input type="submit" value="/" name="operation" id="btn-divide"/></p>

                @Html.ValidationMessageFor(model => model.Result)

             </fieldset>
        }
    </div>
    <div id="dvCalculationResult">
        @{ Html.RenderPartial("CalculationPartial", @Model); }
    </div>  

</body>
</html>

_Layout.cshtml(仅标题很重要)

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Styles.Render("~/Content/modify-calc-input-style")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/modify-calc-input-style")
    @Scripts.Render("~/bundles/LoadPartialCalc")
</head>

HomeController.cs

#region /Home/CalculationValidation
public ActionResult CalculationValidation()
{
    return View(new CalculatorModel());
}
[HttpPost]
public ActionResult CalculationValidation(CalculatorModel valModel, string operation)
{
    var num1 = valModel.Number1;
    var num2 = valModel.Number2;
    if (operation == null)
    {
        ModelState.AddModelError("Operation", "No operation type selected");
        return View();
    }
    else
    {
        if (ModelState.IsValid)
        {
            switch (operation)
            {
                case "+":
                    valModel.Result = num1 + num2;
                    break;
                case "-":
                    if (ValidateNumbers(num1, num2, "-"))
                    {
                        valModel.Result = num1 - num2;
                    }
                    else
                    {
                        valModel.Result = 0;
                        ModelState.AddModelError("Result", "Minus can't be lower than 0");
                    }
                    break;
                case "*":
                    valModel.Result = num1 * num2;
                    break;
                case "/":
                    if (ValidateNumbers(num1, num2, "/"))
                    {
                        valModel.Result = num1 / num2;
                    }
                    else
                    {
                        valModel.Result = 0;
                        ModelState.AddModelError("Result", "Division not whole.");
                    }
                    break;
                default:
                    valModel.Result = 0;
                    break;
            }
        }
    }
    return PartialView("CalculationPartial", valModel);
}
#endregion

CaclculationPartial.cshtml

@using MVCPluginTest.Models
@model MVCPluginTest.Models.CalculatorModel

<h2>Result</h2>
<p id="result">@Model.Result</p>

CalculatorModel

public class CalculatorModel
{
    [Required(ErrorMessage = "Please enter a number.")]
    [Display(Name = "Number 1")]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "You can only enter numbers above 0.")]
    public double Number1
    {
        get;
        set;
    }
    [Required(ErrorMessage = "Please enter a number.")]
    [Display(Name = "Number 2")]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "You can only enter numbers above 0.")]
    public double Number2
    {
        get;
        set;
    }
    public string OperationType
    {
        get;
        set;
    }
    public double Result
    {
        get;
        set;
    }
}

提交点击之前的部分视图

提交点击后的局部视图(主要内容消失了)

在此先感谢您的帮助!

在Sandip Patel最初的回答之后进行更新: 单击提交按钮(#btn-plus)后,将使用参数长度= 15"(URL变为:Home/CalculationValidation?Length = 15)进行重定向.只有partialView加载到其他页面上(没有主要内容).我认为这与我开始填写表格的方式有关.

Update after Sandip Patel's initial anwser: After clicking on the submit button (#btn-plus) the redirection occurs with a parameter of "Length = 15" (URL becomes: Home/CalculationValidation?Length=15). Only the partialView loads on a different page (no main content). I assume it has something to do with the way I Begin the Form.

@using (Html.BeginForm("#ValidationForm"))

就像我以

@using (Html.BeginForm("CalculationValidation", "Home", FormMethod.Post))

页面会进行计算,但会完全重新加载(主要内容和PartialView). 我不确定URL的更改是否导致我的PartialView无法正确更新,那么我也不确定为什么首先会更改URL.

the page does the calculations but it reloads fully (Main content and PartialView). I'm not sure if the alteration to the URL is causing my PartialView to not update correctly, then I'm also not sure WHY it alters the URL in the first place.

推荐答案

在表单提交上设置 event.preventDefault(),它将限制页面刷新.

Set event.preventDefault() on form submit, it will restrict the page to refresh.

$(#ValidationForm").serialize()将序列化您的数据,并传递给您的操作.

$("#ValidationForm").serialize() will serialize your data and that pass to your action.

$("#ValidationForm").submit(function (event) {
event.preventDefault();       

$.ajax({
    url: '@Url.Action("CalculationValidation", "Home")',
    dataType: 'json',
    data: $("#ValidationForm").serialize(),
    type: 'POST',
    success: function (result) {
        $("#dvCalculationResult").html(result);
    },
    error: function (xhr) {
    }
});
});

这篇关于提交点击后仅更新(刷新)PartialView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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