【问题标题】:MVC Core 3.1 and Vue/Axios Posting Null ValuesMVC Core 3.1 和 Vue/Axios 发布 Null 值
【发布时间】:2020-06-10 10:05:45
【问题描述】:

我在让 ASP.Net MVC Core 3.1 将数据发布到 Create 控制器方法时遇到问题。有人能告诉我我错过了什么吗?我的代码在Create 控制器方法中遇到断点,但参数始终为空。
理想情况下,我想将表单数据作为 JSON 发送,并让 JSON.Net 将其转换为对象。我目前正在处理的来源是:https://github.com/encouragingapps/DebtRefresh

这是我的控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DebtRefresh.WebUI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DebtRefresh.WebUI.Controllers
{
    public class CreditCardController : Controller 
    {
        // GET: CreditCard
        public ActionResult Index()
        {
            return View();
        }

        // GET: CreditCard/Details/5
        //public ActionResult Details(int id)
        //{
        //    return View();
        //}

        // GET: CreditCard/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: CreditCard/Create
        [HttpPost]        
        public ActionResult Create([FromBody]String CardVendor)
        {
            try
            {

                String card;
                card = CardVendor;


                // THIS CODE ALWAYS RETURNS NULL DATA No matter what I try


                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: CreditCard/Edit/5
        //public ActionResult Edit(int id)
        //{
        //    return View();
        //}

        // POST: CreditCard/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: CreditCard/Delete/5
        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        // POST: CreditCard/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}

这里是vue代码:

var app = new Vue({
    el: '#app',
    data: {
        CardVendor: '',
        CardNickname: '',
        CreditCardType: '',
        CardLimit: '',
        CardBalance: '',
        InterestRates: [
            {
                interestRate: '0.30',
                startDate: '1/1/2020',
                endDate: '6/30/2020'
            },
            {
                interestRate: '0.60',
                startDate: '7/1/2020',
                endDate: '12/31/2020'
            }
        ]
    },
    methods: {
        addInterestRate: function (event) {                   
            this.interestRates.push({});
        },
        removeInterestRate: function (event) {            
            this.interestRates.pop({});
        },    
        addCard: function (event) {
            //alert(JSON.parse(JSON.stringify(app.$data)));
      
            axios
                .post('/CreditCard/Create', {
                    data: this.CardVendor                    
                }).then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        }    

    }
})

这里是视图:

@{
    ViewData["Title"] = "Add Credit Card";
}
<h1>
    Add Credit Card
</h1>
<div id="app">
    <!--Vue App Start-->
    <label>Credit Card Vendor Name:</label>
    <br />
    <input v-model="CardVendor" placeholder="[Enter Credit Card Vendor Name]" size="50">
    <br /><br />

    <label>Credit Card Nick Name:</label>
    <br />
    <input v-model="CardNickname" placeholder="[Enter Credit Card Nickname]" size="50">
    <br /><br />

    <label>Credit Card Type:</label>
    <br />
    <select v-model="CreditCardType">
        <option value="1">Visa</option>
        <option value="2">Mastercard</option>
        <option value="3">Discover</option>
        <option value="4">American Express</option>
        <option value="5">Other</option>
    </select>

    <br /><br />

    <label>Credit Card Credit Limit:</label>
    <br />
    <input v-model="CardLimit" placeholder="[Enter Credit Card Limit]" size="50">
    <br /><br />

    <label>Credit Card Credit Balance:</label>
    <br />
    <input v-model="CardBalance" placeholder="[Enter Credit Card Balance]" size="50">
    <br /><br />

    <label>Add Interest Rate(s):</label>
    <table border="1">
        <thead>
            <tr>
                <th>Interest Rate %</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(item,index) in InterestRates">
                <td><input type="text" v-model="item.interestRate"></td>
                <td><input type="text" v-model="item.startDate"></td>
                <td><input type="text" v-model="item.endDate"></td>
                <td><button type="button" v-on:click="removeInterestRate(item)">Remove</button>
            </tr>
        </tbody>
    </table>

    <button v-on:click="addInterestRate">Add Interest</button>

    <br />
    <br />

    <button v-on:click="addCard">Add Card</button>

    <br />
    <br />
    <font color="gray">CardVendor-debug: {{ CardVendor }}</font><br />
    <font color="gray">CardNickname-debug: {{ CardNickname }}</font><br />
    <font color="gray">Creditcardtype-debug: {{ CreditCardType }}</font><br />
    <font color="gray">CardLimit-debug: {{ CardLimit }}</font><br />
    <font color="gray">CardBalance-debug: {{ CardBalance }}</font><br />
    
    <!--Vue App End-->
</div>

@section Scripts{
    <script src="~/lib/vue/vue.js"></script>
    <script src="~/lib/axios/axios.js"></script>
    <script src="~/js/addcreditcard.js"></script>
}

我错过了什么?

【问题讨论】:

    标签: vue.js axios asp.net-core-mvc


    【解决方案1】:

    在 Vue 中,您发送的对象是这样的:

    {
        data: this.CardVendor                    
    }
    

    但是您的控制器 Create 方法只接受字符串输入而不是对象,因此它是 NULL。

    [HttpPost]        
    public ActionResult Create([FromBody]String CardVendor)
    

    修复:(1) Either修改c#控制器以接收对象而不是字符串。 因此,请修改您的控制器操作以接收如下对象:

    [HttpPost]        
    public ActionResult Create([FromBody]CardVendorModel cardVendorModel)
    

    并定义一个 C# 模型如下:

    public class CardVendorModel
    {
        public string data {get; set;}
    }
    

    (2)修改 Vue 代码以向 MVC 控制器操作发送字符串,如下所示:

    axios.post('/CreditCard/Create', 
      '\'' + this.CardVendor + '\'')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
    

    【讨论】:

    • 我选择了第一个选项,效果很好!!太感谢了!!你帮我省了好几个小时的头痛!
    • 这是一篇很棒的文章,我发现它与您所说的完全一致! adeyinkaseun.com/2017/07/28/…
    • 工作代码现已发布至:github.com/encouragingapps/DebtRefresh
    • 很高兴它有帮助。另外,谢谢你的链接。确实不错。
    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2021-03-26
    • 2021-01-30
    • 2017-10-02
    • 2020-01-15
    • 2021-04-28
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多