我从控制器正确访问模型时遇到问题我相信,因为我的代码中有一个下拉列表,用于更改用户总数的货币,我有单独的下拉列表,当选择更改时用户根据其选择的当前总数。我能够根据他们选择的选项正确填充总数,但如果我尝试更改货币,它总是将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>
答案 0 :(得分:1)
问题在于changeCurrency
方法
if ((newCurrency != defaultCurrency) && (model.Price > 0))
{
return convertCurrency(currentPrice, newCurrency);
}
由于您通过ajax调用model.Price
方法,而不是通过提交表单, changeCurrency
将始终为0。您需要将当前未格式化的价格从视图传递到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调用执行类似的操作。