我有一个奇怪的情况。我使用
BeginForm
ASP.NET MVC中的助手。通常,如果您在视图上使用视图模型,那么它会将视图模型发布到我的控制器。
现在它将命中我的HTTPGET方法,它没有参数。我最好的猜测是视图模型没有被发送回服务器。
我在下面附上了我的视图、控制器和视图模型代码。
提交表单时,如何确保我的HttpPost方法被命中?我做错了什么吗?
我的观点
:
@using LetterAmazer.Websites.Client.Extensions
@model LetterAmazer.Websites.Client.ViewModels.CreditsViewModel
<h1>Buy credits</h1>
You currently have @Model.Credit.ToFriendlyMoney() credits.
<h3>How many credits do you want to purchase?</h3>
@using (Html.BeginForm("Credits", "User", FormMethod.Post))
{
@Html.EditorFor(model => model.PurchaseAmount) <text>($)</text>
<h3>Select payment method</h3>
@Html.DropDownListFor(model => model.SelectedPaymentMethod, Model.PaymentMethods, new { @class = "form-control" })
<input type="submit" class="btn btn-primary btn-lg" value="Purchase credits" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#@Html.IdFor(model=>model.PurchaseAmount)').change(function () {
var value = $('#@Html.IdFor(model => model.PurchaseAmount)').val();
if (value <= 1) {
$('#@Html.IdFor(model=>model.PurchaseAmount)').val('1');
}
});
});
</script>
我的控制器:
[HttpGet]
public ActionResult Credits()
{
CreditsViewModel model = new CreditsViewModel();
model.Credit = SessionHelper.Customer.Credit;
model.CreditLimit = SessionHelper.Customer.CreditLimit;
var possiblePaymentMethods =
paymentService.GetPaymentMethodsBySpecification(new PaymentMethodSpecification()
{
CustomerId = SessionHelper.Customer.Id
});
foreach (var possiblePaymentMethod in possiblePaymentMethods)
{
model.PaymentMethods.Add(new SelectListItem()
{
Text = possiblePaymentMethod.Name,
Value = possiblePaymentMethod.Id.ToString()
});
}
return View(model);
}
[HttpPost]
public ActionResult Credits(CreditsViewModel model)
{
// stufff
}
我的视图模型:
public class CreditsViewModel
{
public List<SelectListItem> PaymentMethods { get; set; }
public string SelectedPaymentMethod { get; set; }
public int PurchaseAmount { get; set; }
public decimal Credit { get; set; }
public decimal CreditLimit { get; set; }
public CreditsViewModel()
{
this.PaymentMethods = new List<SelectListItem>();
this.PurchaseAmount = 50;
}
}