c# - 表单验证失败时缺少查询字符串参数

标签 c# asp.net-mvc asp.net-mvc-4

我有一个带有以下 url 的表单: CreateEntity?officeCodeId=5

当我发送表单进行验证时,如果验证失败,它只返回 CreateEntity url。没有 officeCodeId=5。

如果用户在 URL 或 F5 上单击输入 - 我的站点失败 - 它需要缺少 officecodeId 参数。我可以将它保存到 session 或其他存储中。但我想把它放在 URL 中

我的看法:

[HttpGet]
        public virtual ActionResult CreateEntity(int? officeCodeId)
        {            
            var model = new CreateViewModel();
            FillViewModel(model, officeCodeId);
            return View("Create", model);
        }


[HttpPost]
protected virtual ActionResult CreateEntity(TEditViewModel model)
        {
            if (ModelState.IsValid)
            {
              //Do some model stuff if 
            }

            return View("Create", model);
        }

编辑。 我的观点:

using (Html.BeginForm("CreateEntity", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.HiddenFor(x => x.OfficeCodeId)  
<div>
                @Html.LabelFor(model => model.FirstName, CommonRes.FirstNameCol)
                @Html.TextBoxFor(model => model.FirstName, Model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
            <div>
                @Html.LabelFor(model => model.LastName, CommonRes.LastNameCol)
                @Html.TextBoxFor(model => model.LastName, Model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
<div> <div class="input-file-area"></div>
                    <input id="Agreements" type="file" name="Agreements"/>
</div>   

编辑 2。 添加:

@using (Html.BeginForm("CreateEntity", "Employee", FormMethod.Post, new { officeCodeId = Model.OfficeCodeId, enctype = "multipart/form-data" }))

没有帮助。 它产生以下形式:

<form action="/PhoneEmployee/CreateEntity" enctype="multipart/form-data" method="post" officecodeid="5">

解决方案是

<form action="@Url.Action("CreateEntity", "Employee")?officecodeid=@Model.OfficeCodeId" enctype="multipart/form-data" method="post">

最佳答案

问题是您的 HttpPost 操作没有任何 id 参数的概念。如果你想支持类似的 URL,那么让 Action 签名支持该参数,例如

[HttpGet]
public ActionResult CreateEntity(int? officeCodeId)

[HttpPost]
public ActionResult CreateEntity(int officeCodeId, EditViewModel model);

关于c# - 表单验证失败时缺少查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789238/

相关文章:

c# - 为什么标志枚举通常用十六进制值定义

asp.net - 集合已修改;枚举操作可能无法执行MVC

asp.net-mvc - 将 http ://mydomain. com/ctrlr/act/val 转发到 http ://WWW. mydomain.com/ctrlr/act/val

asp.net-mvc - 具有默认日期的MVC4日期选择器

javascript - 无法从 Razor 'IF' 语句调用 Javascript 方法

asp.net-mvc-4 - MVC 4 日期文化问题?

c# - 将数据从模型传递到 View 模型并返回 JSON MVC 5

c# - 使用 C++ 保存 wav 文件时音频数据不正确(基于 C# 程序)

c# - 使用 ajax 返回结果更新 ViewModel

c# - 字符在字符串数组中出现的最大次数