Httppost action returning null values

Asked

Viewed 344 times

1

I am developing a web system (intranet) to control requests in ASP.NET MVC 4 C#. Below follow my MVC where I have doubt. I am having a great difficulty with the Httppost of a Typed View, which is returning null value to the "REQUESTER" property of the "Solic" object. This property is of the type "User". What am I doing wrong? From now on, I apologize if I am not being clear with my doubt. I am new in 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");
        }
     }
  • Usuario is also a Model of your Intranet?

  • Hello Gypsy! Yes it is a Model. Our friend Renato gave a solution that worked, but if you have any other suggestion will also be welcome. You can never have too much knowledge.

2 answers

0

Good night!

Dear Members, I have the same problem, could you help me, please.

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

For testing, I created a small and very simple project, putting only one Model User (id, user, password).

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

I even have 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();
            }
        }

0


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

My suggestion is to create a field IdSolicitante in class Solic and render this in a field like hidden in your view for it to be submitted back to the controller.

In class:

public String IdSolicitante { get; set; }

In view:

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

In the controller in the method that generates the view:

solic.IdSolicitante = System.Environment.UserName;

In the controller in the saving method:

solic.SOLICITANTE = new Usuario().ObterUser(solic.IdSolicitante);
  • Renato, thank you so much! It worked! In fact, I only had to insert your suggestion into the controller because the requester id is a property already contained in the User object.

  • Just complementing the comment above: I was passing the solic object.REQUESTER, which is of the User type, to the View, but I did not know that it is not submitted back, being necessary this procedure. Grateful for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.