从我的控制器获取信息到onclick确认(警报)

oCc*_*ing 5 c# asp.net-mvc jquery razor

我试图确认销售,我需要有关产品的总和信息..

我的看法

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
<fieldset>
    <legend>Card</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.CardModel.SerialNumber, new { id = "sn" })
        @Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
    </div>

      <p>
        <input type="submit" value="CardSale" id="btnSubmit"
        onclick="if (confirm('The owner dealer price is : **@Model.OwnerPrice** . Are you sure?')) { return true; } else { return false; }" />
    </p>

</fieldset>
}           
Run Code Online (Sandbox Code Playgroud)

我尝试使用'$ .getJSON'这样:

<script type="text/javascript">
$(document).ready(function() 
 {
  $("#btnSubmit").click(function ()
  {
        var serial = $("#sn");
        var price = "";
        var url = "";
        url = "@Url.Action("GetOwnerPrice","Card")/"+serial;

        $.getJSON(url,function(data)
        {   
            alert(data.Value);
        });
    });       
 });
Run Code Online (Sandbox Code Playgroud)

并在控制器上

 public ActionResult GetOwnerPrice(int sn)
    {
        var owner = db.Dealers.Single(s => s.DealerID == db.Dealers.Single(o => o.UserName == User.Identity.Name).OwnerDealerID);
        var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == sn).SalePrice;

        return Json(ownerPrice, JsonRequestBehavior.AllowGet);
    }
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将它返回到onclick确认消息或我的ViewModel ..

任何帮助?

Hea*_*her 3

按照您编写的方式,在页面生成期间必须知道 @Model.OwnerPrice 值,因为模板引擎在进行模板数据合并时仅具有模型中存在的值。

如果您在页面加载期间确实知道该值,则只需完全按照您的模型中的值使用该值,并且如果用户访问此对话框,他们将看到正确的值。

如果在页面加载期间未知此确认对话框的值,那么您有正确的想法通过 Ajax 调用检索它。诀窍是在调用完成时使用新信息更新 DOM。您可以通过三个步骤完成此操作。首先,更改对话框:

第一的:

if (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
Run Code Online (Sandbox Code Playgroud)

第二:声明一个新的全局变量:

var ownerDealerPrice;
Run Code Online (Sandbox Code Playgroud)

第三:获取价格:

$.ajax({ url: "/GetOwnerPrice", type: "GET", data: "serial=" + serial })
.success(function (price) {ownerDealerPrice = price; }
});
Run Code Online (Sandbox Code Playgroud)