当我从控制器访问模型时,没有获得任何数据

本文关键字:数据 任何 控制器 访问 模型 | 更新日期: 2023-09-27 18:30:34

我相信我在从

控制器正确访问模型时遇到问题,因为我的代码中有一个下拉列表,可以更改用户总数的货币,并且我有单独的下拉列表,选择时会根据用户的选择更改用户的当前总数。我能够根据他们选择的选项正确填充总数,但如果我尝试更改货币,它总是将model.Price显示为 0,这显然是一个错误。我仍然是MVC的新手,但我阅读了它,我认为我正确地访问了model.Price

这是我的模型代码

public class WritingAppModel
{
    // ... other existing properties
    [Required(ErrorMessage = "Price is Required.")]
    [Range(0.01, 10000.00, ErrorMessage = "Your quote is not complete because you haven't completed all of the steps.")]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:C}")]
    public decimal Price { get; set; }
}

控制器

WritingAppModel model = new WritingAppModel();
public JsonResult getNewPrice(modelData dropdownValues)
{
    // check for urgency first since that is the base price
    if (dropdownValues.urgency != null)
    {
        currentPrice = Convert.ToDecimal(dropdownValues.urgency);
        if (dropdownValues.documentType != null)
        {
            currentPrice = currentPrice + Convert.ToDecimal(dropdownValues.documentType);
            if (dropdownValues.numberOfPages != null)
            {
                currentPrice = currentPrice * Convert.ToInt16(dropdownValues.numberOfPages);
            }
        }
    }
    model.Price = currentPrice;
    // do something with value and return a decimal
    return Json(new { currentPrice = model.Price.ToString("C") }, JsonRequestBehavior.AllowGet);
}
public decimal changeCurrency(string newCurrency)
{
    // if this is the first time then make sure current currency is set to dollar
    if (defaultCurrency == null)
    {
        defaultCurrency = "USD";
    }
    // see if new currency is different
    if ((newCurrency != defaultCurrency) && (model.Price > 0))
    {
        return convertCurrency(currentPrice, newCurrency);
    }
    else
    {
        // if nothing changes
        return currentPrice;
    }
}
public decimal convertCurrency(decimal amount, string toCurrency)
{
    WebClient client = new WebClient();
    decimal rate = 0;
    string url = String.Format("https://openexchangerates.org/api/latest.json?app_id={0}", ConfigurationManager.AppSettings["OpenExchangeRate_AppID"]);
    using (StreamReader r = new StreamReader(client.OpenRead(url)))
    {
        string json = r.ReadToEnd();
        var items = JsonConvert.DeserializeObject<Currency>(json);
        if (toCurrency == "EUR")
        {
            rate = items.rates.EUR * amount;
        }
        if (toCurrency == "GBP")
        {
            rate = items.rates.GBP * amount;
        }
    }
    return Math.Round(rate, 2);
}

阿贾克斯调用

$(document).ready(function () {
    $('#currencyList').change(function () {
        $.ajax({
            type: "GET",
            url: "/Home/changeCurrency?newCurrency=" + this.value,
            async: true,
            success: function (result) {
                $('#priceLabel').html(result);
            }
        });
    });

视图

@Html.DropDownListFor(model => model.Currency, (SelectList)ViewBag.currency, null, new { id = "currencyList" })
<h2 id="priceLabel">
    @Html.DisplayFor(model => model.Price)
</h2>

当我从控制器访问模型时,没有获得任何数据

问题是changeCurrency方法中的这段代码

if ((newCurrency != defaultCurrency) && (model.Price > 0))
{
    return convertCurrency(currentPrice, newCurrency);
}

model.Price将始终为 0,因为您通过 ajax 调用changeCurrency方法,而不是通过提交表单。您需要将当前未格式化的价格从视图传递到changeCurrency方法,并将上述块中的model.Price替换为当前价格的十进制等效值。由于价格可以有不同的格式,因此您需要添加新的UnFormattedPrice属性来保存未格式化的价格

public class WritingAppModel
{
    // ... other existing properties
    [Required(ErrorMessage = "Price is Required.")]
    [Range(0.01, 10000.00, ErrorMessage = "Your quote is not complete because you haven't completed all of the steps.")]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:C}")]
    public decimal Price { get; set; }
    public string UnFormattedPrice
    {
        get
        {
            return this.Price.ToString();
        }
    }
}

然后添加一个隐藏字段来保存未格式化的价格

<h2 id="priceLabel">
    @Html.DisplayFor(model => model.Price)
</h2>
@Html.HiddenFor(model => model.UnFormattedPrice)

changeCurrency方法应具有新的 price 参数,并返回包含格式化和未格式化价格的 json

public JsonResult changeCurrency(string newCurrency, string price)
{
    // if this is the first time then make sure current currency is set to dollar
    if (defaultCurrency == null)
    {
        defaultCurrency = "USD";
    }
    currentPrice = Convert.ToDecimal(price);
    decimal newPrice = 0;
    // see if new currency is different
    if ((newCurrency != defaultCurrency) && (currentPrice > 0))
    {
        newPrice = convertCurrency(currentPrice, newCurrency);
    }
    else
    {
        // if nothing changes
        newPrice = currentPrice;
    }
    return Json(new { currentPrice = newPrice.ToString("C"), unformattedCurrentPrice = newPrice.ToString() }, JsonRequestBehavior.AllowGet);
}

然后将 $('#UnFormattedPrice') 的值作为 AJAX 调用中的 price 参数传递。当 ajax 调用成功时,将 <h2 id="priceLabel"> 的值设置为格式化的价格,并将 $('#UnFormattedPrice') 的值设置为未格式化的价格。

$('#currencyList').change(function () {
    $.ajax({
        type: "GET",
        url: "/Home/changeCurrency?newCurrency=" + this.value + "&price=" + $('#UnFormattedPrice').val(),
        async: true,
        success: function (result) {
            $('#priceLabel').html(result.currentPrice);
            $('#UnFormattedPrice').val(result.unformattedCurrentPrice);
        }
    });
});

你应该用getNewPrice方法和相关的 ajax 调用做类似的事情。