我是MVC Architechture的新手。我想将模型的数据传递给行动,但我不知道如何通过它。
当我执行以下代码时,我认为它会自动传递模型数据。
View of ShoppingController:
@using (Ajax.BeginForm("MakePayment", "Shopping", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnBegin = "VarifyParameters" }))
{
<table>
<tr>
<td>
First Name *
</td>
<td>
@Html.TextBoxFor(model => model.firstName, new { @id = "txtFName", @class = "text-field" })
</td>
</tr>
<tr>
<td>
Last Name *
</td>
<td>
@Html.TextBoxFor(model => model.lastName, new { @id = "txtLName", @class = "text-field" })
</td>
</tr>
<tr>
<td>
<input type="button" value="Make Payment" onclick="makePayment()" />
</td>
<tr>
<table>
//there are more button here with different functionalities
}
//javascript
function VarifyParameters() {
try {
return false;
} catch (e) {
}
}
我没有获得任何数据。如何通过javascript将所有模型数据传递给操作
//checkoutController
public ActionResult MakePayment(PaymentDetails paymentDetails)
{
//paymentDetails are always null
}
有人可以建议我如何传递模型数据吗?
答案 0 :(得分:1)
您可以使用Html.BeginForm
并将按钮类型更改为submit
:
@using (Html.BeginForm("MakePayment", "Shopping"))
{
<table>
<tr>
<td>
First Name *
</td>
<td>
@Html.TextBoxFor(model => model.firstName, new { @id = "txtFName", @class = "text-field" })
@Html.ValidationMessageFor(model => model.firstName)
</td>
</tr>
<tr>
<td>
Last Name *
</td>
<td>
@Html.TextBoxFor(model => model.lastName, new { @id = "txtLName", @class = "text-field" })
@Html.ValidationMessageFor(model => model.lastName)
</td>
</tr>
<tr>
<td>
<input type="submit" value="Make Payment" />
</td>
<tr>
<table>
}
您必须将[HttpPost]
添加到您的控制器:
//checkoutController
[HttpPost]
public ActionResult MakePayment(PaymentDetails paymentDetails)
{
//your code
}
您也可以使用Ajax.BeginForm
,并且可以使用其OnBegin
,OnSuccess
,OnFailure
功能。像这样:
@using (Ajax.BeginForm("MakePayment", "Shopping", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnBegin = "VarifyParameters" }))
{
<table>
<tr>
<td>
First Name *
</td>
<td>
@Html.TextBoxFor(model => model.firstName, new { @id = "txtFName", @class = "text-field" })
@Html.ValidationMessageFor(model => model.firstName)
</td>
</tr>
<tr>
<td>
Last Name *
</td>
<td>
@Html.TextBoxFor(model => model.lastName, new { @id = "txtLName", @class = "text-field" })
@Html.ValidationMessageFor(model => model.lastName)
</td>
</tr>
<tr>
<td>
<input type="submit" value="Make Payment" />
</td>
<tr>
<table>
}
但是在使用ajax时,请不要忘记在视图中添加jquery.unobtrusive-ajax.min.js
引用。