Binding in text field

1

In my project I have some tables between them one of occurrences and one of users, where a relationship between them of several occurrences for a user.

What happens is that when registering an occurrence I have to reference the user, so that's fine, but how I used scaffolding to create the view and controller , a select list is created and the user is chosen.

But this is not how I want it, because I want it to get the ID of the logged in user and save it to the bank, that I can get the ID from the logged in user, view instead of a select list has a text field and it shows the user name, not the ID . This is something like what happens when creating a select list . It does a bind and shows the name and not the ID , but saves it to the bank.

The select list is set up like this:

No Controller

And just to make it clear, this controller code is commented on because I'm not using a select list, I'm putting it here, in case anyone knows a logic to do with the text field, receive the ID but show the user's name just like in a select list , and that extends to the time of viewing which user gave that occurrence.

Get

ViewBag.UsuarioID = new SelectList(db.Usuarios, "UsuarioID", "Nome");

Post

ViewBag.UsuarioID = new SelectList(db.Usuarios, "UsuarioID", "Nome", ocorrencia.UsuarioID);

Na View

@model SisGAL.Models.Ocorrencia

@{
    ViewBag.Title = "Novo";
    <script type="text/javascript" src="~/Scripts/Mascara.js"></script>
    var diaAtual = DateTime.Now.ToString("dd'/'MM'/'yyyy");
}

<style>
    a {
        font-family: 'Times New Roman', Times, serif;
        color: white;
    }

        a:link {
            text-decoration: none;
        }

        a:hover {
            text-decoration: none;
        }

        a:visited {
            text-decoration: none;
        }

        a:active {
            text-decoration: none;
        }
</style>

<h2>Nova</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Ocorrencia</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.TipoOcorrencia, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.TipoOcorrencia, new { htmlAttributes = new { @class = "form-control" } })*@
                @Html.DropDownList("Tipo", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.TipoOcorrencia, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.DataOcorrencia, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.DataOcorrencia, new { htmlAttributes = new { @class = "form-control" } })*@
                <input type="text" class="form-control text-box single-line" data-val="true" id="DataOcorrencia" name="DataOcorrencia"
                       placeholder="dd/mm/aaaa" onkeyup="formataData(this,event);" maxlength="10" value="@diaAtual" readonly>
                @Html.ValidationMessageFor(model => model.DataOcorrencia, "", new { @class = "text-danger" })
            </div>
        </div>

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

        @*@Html.DropDownList("UsuarioID", null, htmlAttributes: new { @class = "form-control" })*@
                <input type="text" class="form-control text-box single-line" data-val="true" id="UsuarioID" name="UsuarioID"
                       value="@User.Identity.Name" readonly>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Cadastrar" class="btn btn-success" />
                <a href="@Url.Action("Index", "Alunoes")" style="padding-left: 112px;"><input type="button" value="Cancelar" class="btn btn-warning" /></a>
            </div>
        </div>
    </div>
}

<div>
    <span class="btn btn-default">@Html.ActionLink("Voltar para Lista", "Index")</span>    
</div>

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

So how could I do this bind and show the user the name in a text field and save the ID in the database? That is, link the two.

Edit

What's happening is that when it comes to saving the user to an instance, the field waits for long , because that's how I declared ID , and I am putting a string with the username of the logged in user. And at the time of listing and showing the user, show the user's name, not the ID .

Action that saves the data

  public ActionResult Novo([Bind(Include = "OcorrenciaID,TipoOcorrencia,CausaOcorrencia,DescricaoOcorrencia,Status,DataOcorrencia,AlunoID,UsuarioID")] Ocorrencia ocorrencia)
    {
        if (ModelState.IsValid)
        {
            db.Ocorrencias.Add(ocorrencia);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        /*ViewBag.AlunoID = new SelectList(db.Alunos, "AlunoID", "NomeAluno", ocorrencia.AlunoID);*/
        /*ViewBag.UsuarioID = new SelectList(db.Usuarios, "UsuarioID", "Nome", ocorrencia.UsuarioID);*/
       // ViewBag.UsuarioID = ("UsuarioID", "Nome", ocorrencia.UsuarioID);
        Ocorrencias();
        return View(ocorrencia);
    }

The part of the relationship in the Model

 [Display(Name = "Usuário")]
 public long UsuarioID { get; set; }
 public Usuario Usuario { get; set; }
    
asked by anonymous 03.12.2014 / 14:30

2 answers

2

As in DropDownList you have placed value="@User.Identity.Name" , in the form post you will receive the name of the user, not the ID.

An alternative would be to use a hidden with the value of the user ID you want to receive in the post.

Edition:

  

I was thinking about it, but could I put it in code? And not from the DropDownList and yes a text field myself, I do not want to dropdown.

Controller:

public class SeuController : Controller
{
    [HttpGet]
    public ActionResult CadastrarOcorrencia()
    {
        var usuarioLogado = ObterUsuarioLogado();
        ViewBag.UsuarioID = usuarioLogado.Id;
        ViewBag.UsuarioNome = usuarioLogado.Nome;
        return View();
    }
}

View with a textbox displaying the username of the logged in user:

@Html.Hidden("UsuarioID", (string)ViewBag.UsuarioID)
@Html.TextBox("UsuarioNome", (string)ViewBag.UsuarioNome)
    
03.12.2014 / 15:10
2

As far as I understand, you're putting in User.Identity.Name the user name and what you need is the ID. Then you have to fetch the ID that matches the Name that is in User.Identity.Name .

Then on your Controller do the following:

ViewBag.UsuarioIDLogado = db.Usuarios.First(x=>x.Nome == User.Identity.Name).ID;

In View :

@Html.Hidden("UsuarioID", ViewBag.UsuarioIDLogado })

In% w /% of Save do the following:

public ActionResult Novo([Bind(Include = "OcorrenciaID,TipoOcorrencia,CausaOcorrencia,DescricaoOcorrencia,Status,DataOcorrencia,AlunoID,UsuarioID")] Ocorrencia ocorrencia, string UsuarioID)
    {
        long convertUsuarioID;
        long.TryParse(UsuarioID, out convertUsuarioID);
        ocorrencia.UsuarioID = convertUsuarioID;
        if (ModelState.IsValid)
        {
            db.Ocorrencias.Add(ocorrencia);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        /*ViewBag.AlunoID = new SelectList(db.Alunos, "AlunoID", "NomeAluno", ocorrencia.AlunoID);*/
        /*ViewBag.UsuarioID = new SelectList(db.Usuarios, "UsuarioID", "Nome", ocorrencia.UsuarioID);*/
       // ViewBag.UsuarioID = ("UsuarioID", "Nome", ocorrencia.UsuarioID);
        Ocorrencias();
        return View(ocorrencia);
    }
    
03.12.2014 / 16:15