Binding in text field

Asked

Viewed 351 times

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 far so good, only how I used the scaffolding to create the view and controller, create a select list and in it the user is chosen.

But that’s not the way I want it, because I want you to take the ID of the user logged in and saved in the bank, I can already catch this ID of the logged-in user, and in the view instead of a select list has a text field and in it shows the user name, and not the ID. Or is something similar to what happens in the creation of a select list. He makes a bind and displays the name and not the ID, but saves him on the bench.

The select list is mounted like this:

No Controller

And just to clarify, this code from controller is commented because I am 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 name as it occurs in a select list, and that this extends to when viewing which user gave that occurrence.

In the Get

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

In the 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 display the user name in a text field and save the ID ? That is, to link the two.

Edit

What is happening is that when saving the user in an occurrence, the field expects a long, because that’s how I declared ID, and I’m putting a string with the name of the logged-in user. And that at the time of listing and showing the user, show his name, and not the ID.

Action saving 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 relationship part in Model

 [Display(Name = "Usuário")]
 public long UsuarioID { get; set; }
 public Usuario Usuario { get; set; }
  • Your question is very confusing. You can use the scaffolding options or simply choose an option that it does not manage the controls. So you create your controls (textbox, dropdown, etc.) as you want. Can’t tell if you’re having trouble setting up the View or difficulty recording in the bank.

  • That’s what I thought it would be. So what happens is that in view, when saving the User, the field expects a long and I’m saving a string. And I wanted you to show the string in the text box, but save the long... Just as it happens in select list. I think it’s better now, right ?

  • Where you put "No Controller" in your question, wouldn’t it be code that is in your View? "User" gets a "Selectlist" anyway? If you can, enter your View and Controller to try to help.

  • @Renan, done !

2 answers

2


As in the Dropdownlist you put value="@User.Identity.Name", in the form post you will receive the user name and not the ID.

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


Editing:

I was thinking about it, but could I put it in code ? And not Dropdownlist but a text field even, I don’t want 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 logged in user name:

@Html.Hidden("UsuarioID", (string)ViewBag.UsuarioID)
@Html.TextBox("UsuarioNome", (string)ViewBag.UsuarioNome)
  • I was thinking about it, but could I put it in code? And not Dropdownlist but a text field I don’t want dropdown.

2

From what I understand you’re putting in the User.Identity.Name the user name and what you need is the ID. So you have to search in the flock the ID that corresponds to the Name that is in User.Identity.Name.

So in your Controller do the following:

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

In the View:

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

In the Action to 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);
    }

Browser other questions tagged

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