【发布时间】: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