我有一个Asp.Net MVC 3应用程序,单击提交按钮后,我想验证在formcollection参数中传递的信息..如果无效,我返回一个jSon ..但是在那之后,我的formcollection始终返回null

这发生在chrome和FFox中​​..在IE中工作正常

我的看法:

<li id="opc-register" class="section allow">
    <div id="checkout-step-register" class="step a-item" style="display: none;">
        <form id="co-register-form" action="">
        <div id="checkout-register-load">
            @Html.Action("OpcRegisterForm", "Checkout")
        </div>
        </form>
        <script type="text/javascript">
            Register.init('#co-register-form', '@(storeLocation)checkout/OpcSaveRegister/');
        </script>
        <div class="buttons" id="register-buttons-container">
            <button type="button" class="paymentmethodnextstepbutton" onclick="Register.save()">
                <span>@T("Common.Continue")</span>

            </button>

            <span class="please-wait" id="register-please-wait" style="display: none;">
                <img src="@Url.Content("~/Content/Images/ajax_loader_small.gif")"
    alt="@T("Common.LoadingNextStep")" title="@T("Common.LoadingNextStep")" />
                @T("Common.LoadingNextStep")</span>
        </div>
    </div>
</li>


我的控制器

[HttpPost]
public ActionResult OpcSaveRegister(FormCollection form)
{

    var registerModel = PrepareRegisterModel();

    registerModel.Email = form["Email"];
    registerModel.FirstName = form["FirstName"];
    ...

    if (TryValidateModel(registerModel))
    {
       ....
    }

    //If we got this far, something failed, redisplay form
    return Json(new
    {
        update_section = new UpdateSectionJsonModel()
        {
            name = "register",
            html = RenderPartialViewToString("OpcRegister", registerModel)
        },
        goto_section = "register"
    });
}

最佳答案

不要在带有MVC的帖子上使用FormCollection。使用强类型的ViewModel,其中包含可以在表单上的帖子中提交的所有属性。

例如,您可以有一个类似的类:

public class RegisterViewModel
{
    public string FirstName { get; set; }
    public string Email { get; set; }
    //...
}


在您看来,您可以通过以下方式设置这些属性:

@Html.EditorFor(m => m.FirstName)
@Html.EditorFor(m => m.Email)


然后为您的动作准备

[HttpPost]
public ActionResult OpcSaveRegister(RegisterViewModel registerModel)
{
    //...
}

关于javascript - 提交后,Asp.Net MVC 3 formcollection丢失数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10302484/

10-12 13:26