gpt4 book ai didi

javascript - 使用 MVC 4 从 View 传递模型数据但不显示在操作中

转载 作者:行者123 更新时间:2023-12-03 06:26:51 27 4
gpt4 key购买 nike

我是 MVC 架构的新手。我想将模型的数据传递给操作,但我不知道如何传递它。

我认为当我执行以下代码时它会自动传递模型数据。

ShoppingController View :

@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
}

有人可以建议我如何传递模型数据吗?

最佳答案

您可以使用 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] 添加到您的 Controller :

//checkoutController
[HttpPost]
public ActionResult MakePayment(PaymentDetails paymentDetails)
{
//your code
}

您还可以使用Ajax.BeginForm,并且可以使用其OnBeginOnSuccessOnFailure函数。像这样:

@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 时,不要忘记在 View 中添加 jquery.unobtrusive-ajax.min.js 引用。

关于javascript - 使用 MVC 4 从 View 传递模型数据但不显示在操作中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611287/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com