HttpPost action returning null values

1

I'm developing a web (intranet) system for handling requests in ASP.NET MVC 4 C #. Below are my MVC where I have questions. I'm having a hard time with the HttpPost of a Tipada View, which is returning null value for the "REQUEST" property of the "Solic" object. This property is of type "User". What am I doing wrong? Of course, I apologize if I am not being clear with my doubt. I'm new to development. Thank you for your attention!

Model

namespace INTRADCC.Models
{
public class Solic
{
    public Usuario SOLICITANTE { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Título")]
    public string TITULO { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Objetivo / Benefícios")]
    public string DESC_OBJ_BENEF { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Detalhamento")]
    public string DETALHAMENTO { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Tipo de Solicitação")]
    public string TIPO { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Impacto no Negócio")]
    public string IMPACTO { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Principal Sistema Envolvido")]
    public string SISTEMA_PRINCIPAL { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Frequência da Execução")]
    public string FREQ_EXEC { get; set; }

    [Required(ErrorMessage="Campo Obrigatório!")]
    [Display(Name="Área Executante")]
    public string AREA_EXEC { get; set; }

View

@model INTRADCC.Models.Solic

@{
    ViewBag.Title = "Cadastrar Solicitação";
}

<h2>Cadastrar Solicitação</h2>

@using (Html.BeginForm("CadastrarSolic", "Solic", FormMethod.Post))
{ 
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Solicitante</legend>
        <br />
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.MATRICULA):</b> @Html.DisplayFor(x => x.SOLICITANTE.MATRICULA)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.NOME):</b> @Html.DisplayFor(x => x.SOLICITANTE.NOME)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.USERNAME):</b> @Html.DisplayFor(x => x.SOLICITANTE.USERNAME)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.TELEFONE):</b> @Html.DisplayFor(x => x.SOLICITANTE.TELEFONE)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.EMAIL):</b> @Html.DisplayFor(x => x.SOLICITANTE.EMAIL)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.NOME_GERENCIA_FUNCIONAL):</b> @Html.DisplayFor(x => x.SOLICITANTE.NOME_GERENCIA_FUNCIONAL)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.NOME_GERENCIA_SENIOR):</b> @Html.DisplayFor(x => x.SOLICITANTE.NOME_GERENCIA_SENIOR)</div>
        <div><b>@Html.LabelFor(x => x.SOLICITANTE.NOME_DIRETORIA):</b> @Html.DisplayFor(x => x.SOLICITANTE.NOME_DIRETORIA)</div>

   </fieldset>

    <fieldset>
        <legend>Informações Gerais</legend>

        <div class="editor-label">@Html.LabelFor(x => x.TITULO)</div>
        <div class="editor-field">
            @Html.EditorFor(x => x.TITULO)
            @Html.ValidationMessageFor(x => x.TITULO)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.DESC_OBJ_BENEF)</div>
        <div class="editor-field">
            @Html.TextAreaFor(x => x.DESC_OBJ_BENEF, new {cols="60"})
            @Html.ValidationMessageFor(x => x.DESC_OBJ_BENEF)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.DETALHAMENTO)</div>
        <div class="editor-label">
            @Html.TextAreaFor(x => x.DETALHAMENTO, new {cols="60"})
            @Html.ValidationMessageFor(x => x.DETALHAMENTO)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.TIPO)</div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.TIPO, (SelectList)ViewBag.ListaDeTipo, "Selecione")
            @Html.ValidationMessageFor(x => x.TIPO)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.SISTEMA_PRINCIPAL)</div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.SISTEMA_PRINCIPAL, (SelectList)ViewBag.ListaDeSistemas, "Selecione")
            @Html.ValidationMessageFor(x => x.SISTEMA_PRINCIPAL)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.FREQ_EXEC)</div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.FREQ_EXEC, (SelectList)ViewBag.ListaDeFreqExec, "Selecione")
            @Html.ValidationMessageFor(x => x.FREQ_EXEC)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.IMPACTO)</div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.IMPACTO, (SelectList)ViewBag.ListaDeImpactos, "Selecione")
            @Html.ValidationMessageFor(x => x.IMPACTO)
        </div>

        <div class="editor-label">@Html.LabelFor(x => x.AREA_EXEC)</div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.AREA_EXEC, (SelectList)ViewBag.ListaDeAreaExec, "Selecione")
            @Html.ValidationMessageFor(x => x.AREA_EXEC)
        </div>

        <p><input type="submit" value="Cadastrar" /></p>

    </fieldset>
}
@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

Controller

    [PermissoesFiltro(Roles = "US, AN, GF, GS, AD")]
    public ActionResult CadastrarSolic()
    {

        Solic solic = new Solic();

        solic.SOLICITANTE = new Usuario().ObterUser(System.Environment.UserName);

        ViewBag.ListaDeTipo = new SelectList(new[]
        {
            new{Valor = "Acesso"},
            new{Valor = "Análise de Ocorrências"},
            new{Valor = "Campanhas"},
            new{Valor = "Abertura de SO"},
            new{Valor = "Parametrização / Mudança de Regra"}
        },"Valor","Valor");

        ViewBag.ListaDeSistemas = new SelectList(new[]
        {
            new{Valor = "A"},
            new{Valor = "B"},
            new{Valor = "C"}
        },"Valor","Valor");

        ViewBag.ListaDeFreqExec = new SelectList(new[]
        {
            new{Valor = "Pontual"},
            new{Valor = "Diário"},
            new{Valor = "Semanal"},
            new{Valor = "Mensal"},
            new{Valor = "Outros"}
        }, "Valor", "Valor");

        ViewBag.ListaDeImpactos = new SelectList(new[]
        {
            new{Valor = "Sem Impacto"},
            new{Valor = "Baixo"},
            new{Valor = "Médio"},
            new{Valor = "Alto"},
            new{Valor = "Risco"},
        }, "Valor", "Valor");

        ViewBag.ListaDeAreaExec = new SelectList(new[]
        {
            new{Valor = "1", Texto = "A"},
            new{Valor = "2", Texto = "B"},
            new{Valor = "3", Texto = "C"}
        }, "Valor", "Texto");

        return View(solic);

    }

    [HttpPost]
    public ActionResult CadastrarSolic(Solic solic)
    { 
        if (ModelState.IsValid)
        {
            try 
            {
                long num = solic.Inserir(solic);
                return View("SolicCadastrada",num);
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }
        else 
        { 
            return View("Error");
        }
     }
    
asked by anonymous 29.05.2015 / 22:52

2 answers

0

The problem with your code is that you send SOLICITANTE to the view, but do not submit it back.

My suggestion is to create a IdSolicitante field in the Solic class and render it in a hidden field in your view so that it is submitted back to the controller.

In class:

public String IdSolicitante { get; set; }

In view:

@Html.HiddenFor(x => x.IdSolicitante)

No controller in the method that generates the view:

solic.IdSolicitante = System.Environment.UserName;

No controller in saving method:

solic.SOLICITANTE = new Usuario().ObterUser(solic.IdSolicitante);
    
29.05.2015 / 23:11
0

Good evening!

Dear, I'm having the same problem, could you please help me.

I have read several articles but nothing like this, this article expresses my problem well.

To test, I created a small and very simple project, putting only a Model User (id, user, password).

The view I created from the Edit model, does not return the data in the View-typed object in the Edit action, it is always null.

Including, I have the HiddenFor in the view. @Html.HiddenFor (model => model.id)

----
View
----

@model Teste_Binding.Models.Usuario

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit_EditorFor</title>
</head>
<body>
    @using (Html.BeginForm("Edit", "Usuario"))
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Usuario</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.id)

            <div class="form-group">
                @Html.LabelFor(model => model.usuario, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.usuario, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.usuario, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.senha, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.senha, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.senha, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

----------
Controller
----------

        // POST: Usuario/Edit/5
        [HttpPost]
        public ActionResult Edit(Models.Usuario usuario)
        {
            try
            {
                if (usuario != null)
                {
                    return View(usuario);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    
16.09.2017 / 02:27