如何呈现带有表单字段的页面并在另一个页面上验证这些字段

发布于 2024-11-14 17:16:26 字数 4564 浏览 3 评论 0原文

我有一个页面 ProjectField.cshtml ,其中包含项目中的所有字段。 在我的 HTML 页面中是这样的:

@{
    WebSecurity.RequireAuthenticatedUser();

    // Initialize general page variables
    var name = Request.Form["name"];
    var description = Request.Form["description"];
    int groupId;
    if (Request.Form["groupId"] != null)
    {
        groupId = Request.Form["groupId"].AsInt();
    }
    else
    {
        groupId = -1;
    }

    var menutitle = Request.Form["menutitle"];
}
<div>
    <div class="row-project">
        @Html.Label("Grupo: ", "group")
    </div>
    <select id="group" name="group">
        <option value="-1" @{ if(groupId < 0) { <text>selected="true"</text> } } label="--Selecione--">--Selecione--</option>
        <option value="0" @{ if(groupId == 0) { <text>selected="true"</text> } } label="Residencial">Residencial</option>
        <option value="1" @{ if(groupId == 1) { <text>selected="true"</text> } } label="Comercial">Comercial</option>
        <option value="2" @{ if(groupId == 2) { <text>selected="true"</text> } } label="Institucional">Institucional</option>
        <option value="3" @{ if(groupId == 3) { <text>selected="true"</text> } } label="Mostras">Mostras</option>
    </select>
    @Html.ValidationMessage("group")
</div>

<div>
    <div class="row-project">
        @Html.Label("Projeto: ", "project")
    </div>
    @Html.TextBox("project", name)
    @Html.ValidationMessage("project")
</div>

<div>
    <div class="row-project">
        @Html.Label("Título Menu: ", "menutitle")
    </div>
    @Html.TextBox("menutitle", menutitle)
    @Html.ValidationMessage("menutitle")
</div>

<div>
    <div class="row-project">
        @Html.Label("Descrição: ", "description")
    </div>
    @Html.TextArea("description", description, 4, 35, null)
    @Html.ValidationMessage("description")
</div>


<div class="upload">
    <div>
    @Html.Label("Imagens: ", "images")
    </div>
    @FileUpload.GetHtml(
        initialNumberOfFiles:1,
        allowMoreFilesToBeAdded:true,
        includeFormTag:true,
        addText:"Adicionar",
        uploadText:"Salvar")
    @Html.ValidationMessage("images")
</div>
<div class="row center-button clear">
    <!--<input type="submit" name="action" value="Salvar" title="Salvar"/>-->
</div>

在我的页面 Create.cshtml 中,我使用 RederPage 方法来渲染页面 ProjectFields.cshtml 。 查看完整的代码:

@{
        WebSecurity.RequireAuthenticatedUser();

        Layout = "~/Shared/_Layout.cshtml";
        Page.Title = "Novo Projeto";

        // Initialize general page variables
        var name = Request.Form["name"];
        var description = Request.Form["description"];
        int groupId = Request.Form["groupId"].AsInt();
        var menutitle = Request.Form["menutitle"];

        if (IsPost) 
        {   
            // Validate
            if (name.IsEmpty()) 
            {
                ModelState.AddError("project", "Nome do projeto é obrigatório.");
            }

            if (menutitle.IsEmpty()) 
            {
                ModelState.AddError("menutitle", "Título do menu é obrigatório.");
            }

            if (groupId < 0)
            {
                ModelState.AddError("group", "Grupo é obrigatório.");
            }

            if (Request.Files.Count <= 0 || Request.Files[0].ContentLength <= 0)
            {
                ModelState.AddError("images", "Insira pelo menos uma imagem.");
            }

            // Confirm there are no validation errors
            if (ModelState.IsValid)
            {
                 //CODE FOR SAVE DATA...
            }
        }

}

@if (!ModelState.IsValid)
{
    @Html.ValidationSummary("Houve um problema no cadastro de projeto", true, new{ @class="error" })
}
<form id="contact" method="post" enctype="multipart/form-data" action="@Href(@"~\Project\Create")">
    <fieldset>
        @RenderPage(Href("~/Project/Views/ProjectField.cshtml"))
    </fieldset>
</form>

@BindHelpers.Link(Href("~/Project/Index"), "Lista de projetos", "projects", "projects-link")

但是当我发帖时,它没有验证数据。 我注意到它运行发布表单 Create.cshtml,然后立即发布 ProjectField.cshtml,但这将验证字段是否相同 Create.cshtml。

I have a page ProjectField.cshtml which contains all the fields in a project.
In the HTML page I have is this:

@{
    WebSecurity.RequireAuthenticatedUser();

    // Initialize general page variables
    var name = Request.Form["name"];
    var description = Request.Form["description"];
    int groupId;
    if (Request.Form["groupId"] != null)
    {
        groupId = Request.Form["groupId"].AsInt();
    }
    else
    {
        groupId = -1;
    }

    var menutitle = Request.Form["menutitle"];
}
<div>
    <div class="row-project">
        @Html.Label("Grupo: ", "group")
    </div>
    <select id="group" name="group">
        <option value="-1" @{ if(groupId < 0) { <text>selected="true"</text> } } label="--Selecione--">--Selecione--</option>
        <option value="0" @{ if(groupId == 0) { <text>selected="true"</text> } } label="Residencial">Residencial</option>
        <option value="1" @{ if(groupId == 1) { <text>selected="true"</text> } } label="Comercial">Comercial</option>
        <option value="2" @{ if(groupId == 2) { <text>selected="true"</text> } } label="Institucional">Institucional</option>
        <option value="3" @{ if(groupId == 3) { <text>selected="true"</text> } } label="Mostras">Mostras</option>
    </select>
    @Html.ValidationMessage("group")
</div>

<div>
    <div class="row-project">
        @Html.Label("Projeto: ", "project")
    </div>
    @Html.TextBox("project", name)
    @Html.ValidationMessage("project")
</div>

<div>
    <div class="row-project">
        @Html.Label("Título Menu: ", "menutitle")
    </div>
    @Html.TextBox("menutitle", menutitle)
    @Html.ValidationMessage("menutitle")
</div>

<div>
    <div class="row-project">
        @Html.Label("Descrição: ", "description")
    </div>
    @Html.TextArea("description", description, 4, 35, null)
    @Html.ValidationMessage("description")
</div>


<div class="upload">
    <div>
    @Html.Label("Imagens: ", "images")
    </div>
    @FileUpload.GetHtml(
        initialNumberOfFiles:1,
        allowMoreFilesToBeAdded:true,
        includeFormTag:true,
        addText:"Adicionar",
        uploadText:"Salvar")
    @Html.ValidationMessage("images")
</div>
<div class="row center-button clear">
    <!--<input type="submit" name="action" value="Salvar" title="Salvar"/>-->
</div>

In my page Create.cshtml I ride the html using the method RederPage to render page ProjectFields.cshtml .
See the complete code:

@{
        WebSecurity.RequireAuthenticatedUser();

        Layout = "~/Shared/_Layout.cshtml";
        Page.Title = "Novo Projeto";

        // Initialize general page variables
        var name = Request.Form["name"];
        var description = Request.Form["description"];
        int groupId = Request.Form["groupId"].AsInt();
        var menutitle = Request.Form["menutitle"];

        if (IsPost) 
        {   
            // Validate
            if (name.IsEmpty()) 
            {
                ModelState.AddError("project", "Nome do projeto é obrigatório.");
            }

            if (menutitle.IsEmpty()) 
            {
                ModelState.AddError("menutitle", "Título do menu é obrigatório.");
            }

            if (groupId < 0)
            {
                ModelState.AddError("group", "Grupo é obrigatório.");
            }

            if (Request.Files.Count <= 0 || Request.Files[0].ContentLength <= 0)
            {
                ModelState.AddError("images", "Insira pelo menos uma imagem.");
            }

            // Confirm there are no validation errors
            if (ModelState.IsValid)
            {
                 //CODE FOR SAVE DATA...
            }
        }

}

@if (!ModelState.IsValid)
{
    @Html.ValidationSummary("Houve um problema no cadastro de projeto", true, new{ @class="error" })
}
<form id="contact" method="post" enctype="multipart/form-data" action="@Href(@"~\Project\Create")">
    <fieldset>
        @RenderPage(Href("~/Project/Views/ProjectField.cshtml"))
    </fieldset>
</form>

@BindHelpers.Link(Href("~/Project/Index"), "Lista de projetos", "projects", "projects-link")

But when I make the post, it does not validate the data.
I noticed that it runs the post form Create.cshtml and then immediately post the ProjectField.cshtml but that will validate the fields is the same Create.cshtml.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那些过往 2024-11-21 17:16:26

不确定这是否会对您有帮助,但是,我没有看到表单标签(或制作表单标签的帮助器,如果确实有这样的帮助器)。我错过了什么吗?我确实看到您的输入类型“提交”标签,但我看不到表单标签(操作设置为 Create.cshtml)。

希望这有帮助!

not sure if this will help you but, I don't see a form tag (or the helper to make one, if indeed there is such a helper). Am I missing something? I do see your input type "submit" tag, but I couldn't see a form tag (with action set to Create.cshtml).

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文