【问题标题】:Getting no data when I access the model from the controller当我从控制器访问模型时没有获取数据
【发布时间】:2014-11-17 05:54:29
【问题描述】:

I'm having a problem accessing the model from the controller correctly I believe because I have a dropdownlist in my code which changes the currency for the user's total and I have separate dropdownlists that when chosen change the user's current total based on their选择。我能够根据他们选择的选项正确填充总数,但如果我尝试更改货币,它总是将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);
}

Ajax 调用

$(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>

【问题讨论】:

  • 不能关注这个。 getNewPrice 是否相关?你似乎没有在任何地方调用它。 changeCurrency 应该返回一个 JsonResult (就像你对 getNewPrice 所做的那样。changeCurrency 引用 defaultCurrency 但它没有在任何地方初始化,然后它引用 model.Price 这是模型的一个新实例,所以我假设值model.Price 始终为零(除非您在其构造函数中设置了默认值)
  • @StephenMuecke 我只包含它以显示我如何根据他们的选择更改价格,并且模型中保存了一个价格,但我正在尝试使用 changecurrency 函数访问相同的数据它总是零
  • 但是您没有将价格从视图发送到控制器。您所做的只是初始化模型的一个新实例并格式化其价格(其值为零)
  • 好吧,这是有道理的。那么ajax有什么方法可以在不传递模型数据的情况下访问它呢?谢谢你帮我解决这个问题。答案只是没有找到我
  • 我在 ekads 答案中添加了一些 cmets,这可能有助于解决您的问题,但我不完全确定您要做什么。您的 getNewPrice 确实应该发送未格式化的十进制值(然后您将其传递回 changeCurrency 方法)和用于更新显示的格式化货币值。

标签: c# ajax asp.net-mvc asp.net-mvc-3


【解决方案1】:

问题是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 调用。 ajax调用成功后,将&lt;h2 id="priceLabel"&gt;的值设置为格式化后的价格,将$('#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 调用执行类似的操作。

【讨论】:

  • Convert.ToDecimal(price); 如果price 的值已经是格式化的货币字符串,则可能无法工作。可能还需要发布当前格式的文化信息?
  • 在 getNewPrice 方法中返回格式化和未格式化的值可能最简单,然后可以将未格式化的十进制值缓存在客户端上,并将其发送到 changeCurrency 方法的值连同格式字符串。
  • 我认为currentPrice = decimal.Parse(price, NumberStyles....) 也不会起作用,因为它基于服务器上的当前文化解析值,而不是最初传递给客户端的值的文化。
  • 正则表达式也不起作用,因为某些文化使用点作为小数分隔符,而其他文化使用逗号。
  • 我也遇到了麻烦。我愿意尝试任何你认为可行的方法
猜你喜欢
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多