【问题标题】:Pass PartialView with AJAX and still using Controller in MVC on submit使用 AJAX 传递 PartialView 并在提交时仍然在 MVC 中使用 Controller
【发布时间】:2014-03-06 10:02:22
【问题描述】:

我有一个 div,当我按下提交类型的输入时,我想在其中放置一个 PartialView。在 Controlleraction ShowDetail() 执行后,必须在 div 中创建局部视图,否则我在模型中得到空引用。我已经尝试使用 AJAX,但我不确定如何编写,尤其是在将部分视图发布到 div 之前需要创建模型时。我真的很感激一些指导或解决方案

我的视图(应该保留部分视图的 div 是 anCalcDetail):

@using (Html.BeginForm("ShowDetail", "Calculation"))
                    {
                       <div class="calculateBox">
                            <label for="calcOption">Choose value to calculate:</label>
                            <select form="anFormCalcInput" id="calcOption" title="Choose what value you want to calculate">
                                <option value="anPMT">Payment (PMT)</option>
                                <option value="anI">Interest (I)</option>
                                <option value="anFV">Future value (FV)</option>
                                <option value="anPV">Present value (PV)</option>
                            </select>
                        </div>
                        <div class="calculateBox" background-color="#777777">
                            @Html.Label("Present value (PV)")
                            @Html.TextBox("PresentValue")
                            @Html.Label("Future value")
                            @Html.TextBox("FutureValue")
                            @Html.Label("Interest rate")
                            @Html.TextBox("InterestRate") <br />
                            <input type="radio" name="advanceOrArrears" id="inAdvance" value="inAdvance" /> In advance<br />
                            <input type="radio" name="advanceOrArrears" id="inArrears" value="inArrears" /> In arrears
                        </div>
                        <div class="calculateBox">
                            <label for="startDate">Start date:</label>
                            <input type="date" id="anStartDate" name="startdate" title="Choose start date for your calculation" /><br />
                            @Html.Label("Payment frequency")
                            <select form="anFormCalcInput" id="anPmtFreq" title="Choose the payment frequency, for example: Every month">
                                <option value="Monthly">Monthly</option>
                                <option value="Quarterly">Quarterly</option>
                                <option value="Yearly">Yearly</option>
                            </select><br /><br />
                            @Html.Label("No of payment periods")
                            @Html.TextBox("PaymentPeriods")
                            @Html.Label("Date time convention")
                            <select form="anFormCalcInput" id="anDTC" title="Choose your Date time convention">
                                <option value="360360">360/360</option>
                                <option value="365365">365/365</option>
                            </select><br /><br />
                            <input type="submit" id="anCalcBtn" class="calcBtn" name="anSubmitBtn" value="Calculate" title="Calculate your calculation" />
                        </div>
                    }
                    </div>
                    <table cellspacing="0" width="80%">
                    <div class="calcDetail" id="anCalcDetail">
                    </div>

我的部分观点:

@model IEnumerable<CalcFactory.Models.Calculation>

<table cellspacing="0" width="80%">
<thead>
    <tr>
        <th>
            Date
        </th>
        <th>
            Invoice amount
        </th>
        <th>
            Interest rate
        </th>
        <th>
            Interest amount
        </th>
        <th>
            Amortization
        </th>
        <th>
            Capital balance
        </th>
        <th></th>
    </tr>
</thead>
<tr>
    <td align="center">
    </td>
    <td align="center">
    </td>
    <td align="center">
    </td>
    <td align="center">
    </td>
    <td align="center">
    </td>
    <td align="center" id="startValue">
    </td>
</tr>
@foreach (var item in Model) {
<tr>
    <td align="center">
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td align="center">
        @Html.DisplayFor(modelItem => item.InvoiceAmount)
    </td>
    <td align="center">
        @Html.DisplayFor(modelItem => item.InterestRate)
    </td>
    <td align="center">
        @Html.DisplayFor(modelItem => item.InterestAmount)
    </td>
    <td align="center">
        @Html.DisplayFor(modelItem => item.Amortization)
    </td>
    <td align="center">
        @Html.DisplayFor(modelItem => item.PresentValue)
    </td>
</tr>

}

我的控制器(需要在部分视图转储到 div 之前运行):

public ActionResult ShowDetail(FormCollection form)
    {

        List<Calculation> cList = new List<Calculation>();
        Calculation calc = new Calculation();
        calc.Date = Convert.ToDateTime(form["startdate"]);
        calc.InvoiceAmount = 2000;
        calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
        calc.InterestAmount = (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30);
        calc.Amortization = (2000 - (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30));
        calc.PresentValue = Convert.ToDouble(form["PresentValue"]) - calc.Amortization;
        cList.Add(calc);
        for (int i = 0; i < Convert.ToInt32(form["PaymentPeriods"]); i++)
        {
            Calculation calcBefore = cList.Last();
            calc = new Calculation();
            calc.Date = calcBefore.Date.AddMonths(1);
            calc.InvoiceAmount = 2000;
            calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
            calc.InterestAmount = (calcBefore.PresentValue * Convert.ToDouble(form["InterestRate"]) / 360 * 30);
            calc.Amortization = (calc.InvoiceAmount - (calcBefore.PresentValue * calc.InterestRate / 360 * 30));
            calc.PresentValue = calcBefore.PresentValue - calc.Amortization;
            cList.Add(calc);
        }
        return PartialView("ShowDetail", cList);
    }

最后是我的 JS/AJAX 尝试:

$(document).on('click', '#anCalcBtn', function () {
$.post("ShowDetail.cshtml", function (data) {
    //Run the ShowDetail action before the data is posted into the div
    //Post partialview into div-id #anCalcDetail
    $("#anCalcDetail").html(data);
});

});

【问题讨论】:

    标签: javascript jquery html ajax asp.net-mvc


    【解决方案1】:

    资源没有按照你现在在 mvc 中的方式提供。要调用您的 ShowDetail 方法,请将您的 jQuery post 更改为:

    $('#anCalcBtn').on('click', function (e) {
          var form = $('form');
          e.preventDefault();
          $.ajax({ 
              url: 'Calculation/ShowDetail', 
              type: 'POST', 
              data:form.serialize(), 
              dataType: 'json', 
              contentType: 'application/json', 
              success: function (data) { 
                  $("#anCalcDetail").html(data);
         });
    });
    

    确保标记您的 ActionMethod HttpPost

    [HttpPost]
    public ActionResult ShowDetail(FormCollection form)
    { 
           ///usual code
    }
    

    【讨论】:

    • 您的代码仍然将我发送到新视图,并且不会将部分视图粘贴到 div 中
    • 哦,我的错,您必须先停止正常的点击流,然后才能发出请求。立即查看
    • 嘿,看看我的回答,现在您将所有控件数据作为 httpResponse 的数据发送
    • 感觉它不关心ajax,而是运行ShowDetail-action
    • 有什么方法可以检查 ajax-post 是否发送了正确的代码?
    【解决方案2】:

    通过将 Html.BeginForm 更改为 Html.AjaxForm 并使 UpdateTargetId = "anCalcDetail" 它实际上在 .js 中没有 AJAX 调用的情况下工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-10
      • 2014-09-23
      • 1970-01-01
      • 2018-09-01
      • 2014-12-11
      • 1970-01-01
      • 2016-07-07
      • 2011-03-08
      相关资源
      最近更新 更多