【问题标题】:ASPNET Core MVC ajax not passing data correctlyASPNET Core MVC ajax 未正确传递数据
【发布时间】:2021-12-03 04:11:15
【问题描述】:

目标:我正在为我的网站设置结帐页面,并希望用户从他们的地址列表中进行选择。当他们选择它时,它会将其添加到缓存中并将其保存以供他们设置好所有内容并准备完成订单时使用。

问题:选择地址,按保存更改时,返回0而不是项目的实际值,我不知道为什么。

这是表格:

这是视图:

@model AirmotionEcommerceWebsite.Models.Home.CheckoutModel

@{
    ViewBag.Title = "Checkout";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<br />
<div class="container">
    <h1>Checkout</h1>

    <form>
        <div class="jumbotron row product-container">
            <div class="col-md-4">
                @{
                    IEnumerable<SelectListItem> dataItems = ViewBag.UserAddresses;
                }

                <div class="form-group">
                    <h4>To Address:</h4>
                    @Html.DropDownListFor(model => model.selectedShippingAddress.IntShippingAddressId, dataItems, "-- Select --", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.selectedShippingAddress.IntShippingAddressId, "", new { @class = "text-danger" })
                    <a asp-controller="Home" asp-action="AddShippingAddress">Add New Address</a>
                </div>

                <div class="form-group">
                    <button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal" data-target="#ValidateAddress"
                            data-url="@Url.Action("CheckoutChanges", new { intShippingAddressID = Model.selectedShippingAddress.IntShippingAddressId })">Verify Address</button>
                </div>
            </div>



        </div>
    </form>

</div>


<script>
    $(function () {
        $('button[data-toggle="ajax-modal"]').click(function (event) {
            event.preventDefault();
            var url = $(this).data('url');
            // get the form containing the submit button
            var form = $(this).closest('form')
            // serialize all the fields in the form
            var model = form.serialize();
            // the the request to the url along with the form (model) data
            $.get(url, model).done(function (data) {
                PlaceHolderElement.html(data);
            })
        })
    })
</script>

这里是控制器:

[Authorize]
        public ActionResult Checkout()
        {
            // get userid
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            // get addresses for this user
            ViewBag.UserAddresses = GetShippingAddresses(userId);

            CheckoutModel model = new CheckoutModel();
            model.selectedShippingAddress = new TwebShippingAddress();

            bool AlreadyExists = memoryCache.TryGetValue<CheckoutModel>("CachedModel", out model);
            if (!AlreadyExists)
            {
                model = new CheckoutModel();
                model.selectedShippingAddress = new TwebShippingAddress();
                var cachEntryOptions = new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromSeconds(20));
                memoryCache.Set("CachedModel", model, cachEntryOptions);
            }

            return View(model);
        }

        [HttpGet]
        public ActionResult CheckoutChanges(int intShippingAddressID)
        {
            if (intShippingAddressID == 0)
                return View();
            CheckoutModel model = new CheckoutModel();

            bool AlreadyExists = memoryCache.TryGetValue<CheckoutModel>("CachedModel", out model);

            if (AlreadyExists)
            {
                model.selectedShippingAddress = context.TwebShippingAddresses.Where(x => x.IntShippingAddressId == model.selectedShippingAddress.IntShippingAddressId).FirstOrDefault();
                var cachEntryOptions = new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromSeconds(20));
                memoryCache.Set("CachedModel", model, cachEntryOptions);
            }

            return View();
        }

最后,这是 GetShippingAddresses() 方法:

public IEnumerable<SelectListItem> GetShippingAddresses(string strUserID)
        {
            List<SelectListItem> list = new List<SelectListItem>();

            var cat = context.TwebShippingAddresses.Include(x => x.IntState).Where(x => x.IntWebUserId == strUserID).OrderByDescending(x=>x.BlnIsDefault);

            foreach (var item in cat)
            {
                list.Add(new SelectListItem { Value = item.IntShippingAddressId.ToString(), Text = item.StrName + " " + item.StrAttnTo + " " + item.StrStreet1 + " " + item.StrStreet2 + ", " + item.StrCity + " " + item.IntState.StrStateCode + " " + item.StrZip  });
            }
            return list;
        }

【问题讨论】:

  • 因为在服务器端data-url="@Url.Action("CheckoutChanges", new { intShippingAddressID =...})"生成页面时,您已经“烘焙”了id。
  • 那我应该用什么来代替它?

标签: javascript asp.net ajax asp.net-mvc asp.net-core


【解决方案1】:

像这样替换 $.get 以传递一个 Json 对象,该对象将自动绑定到操作的参数:

<script>
    $(function () {
        $('button[data-toggle="ajax-modal"]').click(function (event) {
            event.preventDefault();
            var url = $(this).data('url');
            // get the form containing the submit button
            var form = $(this).closest('form')
            // serialize all the fields in the form
            var model = form.serialize();
            // the the request to the url along with the form (model) data
            
            int selectedIndex = //Write jquery code to get the selected index here
            
            
        $.ajax({
                type: 'GET',
                url: url,
                data: { intShippingAddressID: selectedIndex },
                dataType: 'json',
            })
            .success(function( data ) {         
                PlaceHolderElement.html(data);          
        });
        
        })
    })
</script>

注意与Action的参数匹配的Json数据类型和属性。

【讨论】:

    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多