ASP.NET core 将模型传递给视图时所有模型值均为 null

发布于 2025-01-16 12:30:25 字数 10856 浏览 2 评论 0原文

目标:我有一个页面,我希望有一个通过视图模型传递的返回 url,以便在完成表单后,它将返回到之前的 url。该页面是地址验证并将其作为保存地址添加到帐户中。

页面流程:您将看到一张需要填写的地址表。完成后,您将有一个按钮,该按钮将调用控制器方法,该方法将通过 API 与 FedEx 进行验证,然后如果有效,它会让您保存地址。

问题:按下“验证地址”按钮后,将表单数据发送到控制器时似乎出现问题。

HTTPGET:

public ActionResult AddShippingAddress(string strReturnURL)
{
    // get states
    ViewBag.states = GetStates();
    DeliveryAddressModel model = new DeliveryAddressModel();
    model.strReturnAddress = strReturnURL;
    return View(model);
}

AddShippingAddress.chshtml

@model EcommerceWebsite.Models.Home.DeliveryAddressModel

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


<br />
<div class="container">
    <partial id="ValidateAddress"></partial>

    @using (Html.BeginForm())
    {
        <h4>Shipping Address</h4>
        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            <h5>Name</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Attention To</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strAttnTo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Street</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strStreet1, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Street 2</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strStreet2, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>City</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strCity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strCity, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @{
                IEnumerable<SelectListItem> dataItems = ViewBag.states;
            }
            <div class="form-group">
                <h5>State</h5>
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.State.IntStateId, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <h5>Zip</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strZip, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strZip, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Phone Number</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Set as Default</h5>
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.blnIsDefault)
                    @Html.ValidationMessageFor(model => model.blnIsDefault, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
                        data-url="@Url.Action("GetValidationOnAddress", new { model = Model })">
                    Verify Address
                </button>
            </div>
        </div>
    }
</div>


<script>

    $(function () {
        var PlaceHolderElement = $('#ValidateAddress');
        $('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);
                PlaceHolderElement.find('.modal').modal('show');
                //$('#ValidateAddress').modal('show');
            })
        })
    })

</script>

这是部分内容:

@model EcommerceWebsite.Models.Home.DeliveryAddressModel


<div class="modal fade" id="ValidateAddress">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            @using (Html.BeginForm("AddShippingAddressToUser", "Home"))
            {

                @Html.HiddenFor(x => x.strName)
                @Html.HiddenFor(x => x.strAttnTo)
                @Html.HiddenFor(x => x.strStreet1)
                @Html.HiddenFor(x => x.strStreet2)
                @Html.HiddenFor(x => x.strCity)
                @Html.HiddenFor(x => x.State.StrStateCode)
                @Html.HiddenFor(x => x.State.StrStateName)
                @Html.HiddenFor(x => x.State.IntStateId)
                @Html.HiddenFor(x => x.strZip)
                @Html.HiddenFor(x => x.strPhoneNumber)
                @Html.HiddenFor(x => x.blnIsDefault)
                <div class="modal-body">
                    <form action="Create">
                        <div class="form-group">
                            @if (Model.ErrorMessage == null)
                            {
                                <h5>@Model.strName</h5>
                                @if (Model.strAttnTo != null)
                                {<h5>@Model.strAttnTo</h5>}
                                <h5>@Model.strStreet1</h5>
                                @if (Model.strStreet2 != null)
                                {<h5>@Model.strStreet2</h5>}
                                <h5>@Model.strCity</h5>
                                <h5>@Model.State.StrStateCode</h5>
                                <h5>@Model.strZip</h5>
                                <h5>@Model.strPhoneNumber</h5>

                                <div class="modal-footer">
                                    <button type="submit" value="Save" class="btn btn-primary">Save</button>
                                    <button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
                                </div>
                            }
                            else
                            {
                                <h4>@Model.ErrorMessage</h4>
                            }
                        </div>
                    </form>
                </div>
            }
        </div>
    </div>
</div>

当一切都说完了并且按下获取验证按钮时,它应该将所有数据发送到控制器并使用 FedEx 验证地址。但一切都是空的..

在此处输入图像描述

现在需要注意的是,当我将 httpget 的返回更改为 return View(); 时,一切正常,但不起作用发送URL。

更新:

AddShippingAddressToUser() 尚未被调用。错误位于第 101 - 102 行中的某个位置。按钮内部或家庭控制器上的第 618 行。

输入图像此处描述

更新:这是模型

public class DeliveryAddressModel
    {
        //[Required]
        //[Display(Name = "First & Last Name")]
        public string strName { get; set; }
        //[Display(Name = "Attention To")]
        public string strAttnTo { get; set; }
        //[Required]
        //[Display(Name = "Street 1")]
        public string strStreet1 { get; set; }
        //[Display(Name = "Street 2")]
        public string strStreet2 { get; set; }
        //[Required]
        //[Display(Name = "City")]
        public string strCity { get; set; }
        //[Required]
        //[Display(Name = "State")]
        public Tstate State { get; set; }
        //[Required]
        //[Display(Name = "Zipcode")]
        public string strZip { get; set; }

        //[Required(ErrorMessage = "You must provide a phone number")]
        //[Display(Name = "Phone Number")]
        //[DataType(DataType.PhoneNumber)]
        //[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
        public string strPhoneNumber { get; set; }

        public bool blnIsDefault { get; set; }


        public string ErrorMessage { get; set; }

        public string strReturnAddress { get; set; }

    }

Goal: I have a page that I want to have a return url passed through the model of the view so upon completion of the form, it will return to the previous url. The page is a address validation and add it to the account as a saved address.

Flow of the page: You are presented with an address form to fill out. on completion, you will have a button that will call to a controller method that will verify with FedEx via API, and then if valid, it will let you save the address.

Issue: once you press the Verify Address button, it seems to have an issue with sending the form data to the controller.

HTTPGET:

public ActionResult AddShippingAddress(string strReturnURL)
{
    // get states
    ViewBag.states = GetStates();
    DeliveryAddressModel model = new DeliveryAddressModel();
    model.strReturnAddress = strReturnURL;
    return View(model);
}

AddShippingAddress.chshtml

@model EcommerceWebsite.Models.Home.DeliveryAddressModel

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


<br />
<div class="container">
    <partial id="ValidateAddress"></partial>

    @using (Html.BeginForm())
    {
        <h4>Shipping Address</h4>
        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            <h5>Name</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Attention To</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strAttnTo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Street</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strStreet1, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Street 2</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strStreet2, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>City</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strCity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strCity, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @{
                IEnumerable<SelectListItem> dataItems = ViewBag.states;
            }
            <div class="form-group">
                <h5>State</h5>
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.State.IntStateId, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <h5>Zip</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strZip, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strZip, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Phone Number</h5>
            <div class="col-md-10">
                @Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <h5>Set as Default</h5>
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.blnIsDefault)
                    @Html.ValidationMessageFor(model => model.blnIsDefault, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
                        data-url="@Url.Action("GetValidationOnAddress", new { model = Model })">
                    Verify Address
                </button>
            </div>
        </div>
    }
</div>


<script>

    $(function () {
        var PlaceHolderElement = $('#ValidateAddress');
        $('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);
                PlaceHolderElement.find('.modal').modal('show');
                //$('#ValidateAddress').modal('show');
            })
        })
    })

</script>

Here is the partial:

@model EcommerceWebsite.Models.Home.DeliveryAddressModel


<div class="modal fade" id="ValidateAddress">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            @using (Html.BeginForm("AddShippingAddressToUser", "Home"))
            {

                @Html.HiddenFor(x => x.strName)
                @Html.HiddenFor(x => x.strAttnTo)
                @Html.HiddenFor(x => x.strStreet1)
                @Html.HiddenFor(x => x.strStreet2)
                @Html.HiddenFor(x => x.strCity)
                @Html.HiddenFor(x => x.State.StrStateCode)
                @Html.HiddenFor(x => x.State.StrStateName)
                @Html.HiddenFor(x => x.State.IntStateId)
                @Html.HiddenFor(x => x.strZip)
                @Html.HiddenFor(x => x.strPhoneNumber)
                @Html.HiddenFor(x => x.blnIsDefault)
                <div class="modal-body">
                    <form action="Create">
                        <div class="form-group">
                            @if (Model.ErrorMessage == null)
                            {
                                <h5>@Model.strName</h5>
                                @if (Model.strAttnTo != null)
                                {<h5>@Model.strAttnTo</h5>}
                                <h5>@Model.strStreet1</h5>
                                @if (Model.strStreet2 != null)
                                {<h5>@Model.strStreet2</h5>}
                                <h5>@Model.strCity</h5>
                                <h5>@Model.State.StrStateCode</h5>
                                <h5>@Model.strZip</h5>
                                <h5>@Model.strPhoneNumber</h5>

                                <div class="modal-footer">
                                    <button type="submit" value="Save" class="btn btn-primary">Save</button>
                                    <button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
                                </div>
                            }
                            else
                            {
                                <h4>@Model.ErrorMessage</h4>
                            }
                        </div>
                    </form>
                </div>
            }
        </div>
    </div>
</div>

When all is said and done and the get validation button is pressed, it's supposed to send all the data to the controller and Verify the address with FedEx. But everything is null..

enter image description here

Now something to note, when I change the return of the httpget to return View(); everything works except it doesn't send the URL.

Update:

The AddShippingAddressToUser() hasn't even been called yet. The error lies somewhere in lines 101 - 102. Inside the button or the line 618 on the home controller.

enter image description here

Update: Here's the Model

public class DeliveryAddressModel
    {
        //[Required]
        //[Display(Name = "First & Last Name")]
        public string strName { get; set; }
        //[Display(Name = "Attention To")]
        public string strAttnTo { get; set; }
        //[Required]
        //[Display(Name = "Street 1")]
        public string strStreet1 { get; set; }
        //[Display(Name = "Street 2")]
        public string strStreet2 { get; set; }
        //[Required]
        //[Display(Name = "City")]
        public string strCity { get; set; }
        //[Required]
        //[Display(Name = "State")]
        public Tstate State { get; set; }
        //[Required]
        //[Display(Name = "Zipcode")]
        public string strZip { get; set; }

        //[Required(ErrorMessage = "You must provide a phone number")]
        //[Display(Name = "Phone Number")]
        //[DataType(DataType.PhoneNumber)]
        //[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})
quot;, ErrorMessage = "Not a valid phone number")]
        public string strPhoneNumber { get; set; }

        public bool blnIsDefault { get; set; }


        public string ErrorMessage { get; set; }

        public string strReturnAddress { get; set; }

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自在安然 2025-01-23 12:30:25

首先,由于表单的功能不是检索操作和创建操作,因此请使用 http 动词 POST 而不是 GET。将操作上方的 HttpVerb 过滤器从 HttpGet 替换为 HttpPost。

其次添加以下内容:

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

或者,

    @using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))

在操作中的模型之前添加:[FromQuery]

First thing, since your form's function isnt a retrieval operation and a creational operation, use the http verb POST and not GET. Replace the HttpVerb filter above your action from HttpGet to HttpPost.

Second add this:

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

Alternatively,

    @using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))

Before your model in the action add: [FromQuery]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文