Adding Text Box and Writing to Database. (with C#, entityframework 6.1.3)

Asked

Viewed 234 times

3

I am doing a project in Visual Studio 2013, with Entityframework version 6.1.3, MVC 4.5.0.0 and using Viewmodel.

I am programming a page that is called payment condition. The creation page will have a text field nome, 2 radiobuttons: "the view" and "on time". If the user selects the view nothing will happen.

Now, if the radiobutton "In time" is selected, a button will appear to add textboxes of the days to be filled. I need to make this schedule to add the textboxes as you click the add days button and then make a function to record in the bank.

I think the function of the Add Days button I can do in Jquery, and then the creation button that will add a function in the database Controller.

I know jquery, add the text boxes, now I’m a little lost in the part of c#, the save in the bank made in Controller.

Exemplo

the code below is from my viewmodel:

    [Key]
    [DisplayName("Id")]
    public int CondicaoPagamentoId { get; set; }

    [Required(ErrorMessageResourceName = "PropertyValueRequired", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [MinLength(DataConfig.DATABASE_MIN_LENGTH_DEFAULT, ErrorMessageResourceName = "MinLengthAttribute_ValidationError", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [MaxLength(DataConfig.DATABASE_MAX_LENGTH_DEFAULT, ErrorMessageResourceName = "MaxLengthAttribute_ValidationError", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [DisplayName("Nome")]
    public string Nome { get; set; }

    [Required(ErrorMessageResourceName = "PropertyValueRequired", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [MinLength(DataConfig.DATABASE_MIN_LENGTH_DEFAULT, ErrorMessageResourceName = "MinLengthAttribute_ValidationError", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [MaxLength(DataConfig.DATABASE_MAX_LENGTH_DEFAULT, ErrorMessageResourceName = "MaxLengthAttribute_ValidationError", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [DisplayName("Tipo")]
    public bool Tipo { get; set; }

    [Required(ErrorMessageResourceName = "PropertyValueRequired", ErrorMessageResourceType = typeof(DataAnnotationsResources))]
    [DisplayName("Dias")]
    public int CondicaoPagamentoDiasId { get; set; }
    public virtual CondicaoPagamentoDiasViewModel CondicaoPagamentoDias { get; set; }
    public virtual IEnumerable<CondicaoPagamentoDiasViewModel> CondicaoPagamentoDiass { get; set; }

    [DisplayName("Cadastrado por")]
    public int UsuarioCadastroId { get; set; }
    public virtual UsuarioViewModel UsuarioCadastro { get; set; }

    [DisplayName("Data de Cadastro")]
    public DateTime DataCadastro { get; set; }

the addition is made by:

this.add(objeto)
  • The path is using the Nuget package called Begincollectionitem. Here on the website we have these questions and answers about this package. If you can, edit your question by placing code such as your View, of your Viewmodel, etc., so that I can give a more objective orientation.

  • I didn’t understand which part is "lost", you already have some request, method or something to save the data ?

  • Thiago I save the object: this.add(object), usually. But in this specific case of my question I have two tables (condicaopagamento to keep the name and the type (term or view) and another to save the days (30,90,...) condicaopagamentodias).

  • I don’t know how I’m going to add the days, since it will be a dynamic thing. And not just an object.

  • I believe that be this that you are looking for. Look at the comment of the Gypsy, which has many other examples. In case none of them answer you, post more information on how your controller and its view, to make it easier to help you.

2 answers

3


Well, it’s all right for you to use the Begincollectionitem. Just implement now. My suggestion for the installments starts in the code of View down below:

<div class="condicoes-pagamento" id="condicoes-pagamento">
    @if (Model != null)
    {
        foreach (var condicoesPgto in Model.CondicaoPagamentoDiass)
        {
            @Html.Partial("_CondicoesPagamentoDia", condicoesPgto);
        }
    }
</div>

To Partial _CondicoesPagamentoDia would look like this:

@model MeuProjeto.ViewModels.CondicaoPagamentoDiasViewModel

@using (Html.BeginCollectionItem("CondicaoPagamentoDiass"))
{
    <div class="form-group">
        @Html.HiddenFor(model => model.CondicaoPagamentoDiaId)
        @Html.HiddenFor(model => model.CondicaoPagamentoId)

        <label class="col-md-1 control-label">Dia:</label>
        <div class="col-md-3">
            @Html.TextBoxFor(model => model.Dia, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Dia, "", new { @class = "text-danger" })
        </div>
        <div class="col-md-2">
            <a class="btn red" onclick="$(this).parent().parent().remove();">Excluir</a>
        </div>
    </div>
}

Note that the code already assumes a delete line button in Javascript. There is also an add button that can be implemented as follows:

        <script type="text/javascript">
            $("#adicionar-dia").click(function () {
                $.get('/SeuController/NovaLinhaDia', function (template) {
                    $("#condicoes-pagamento").append(template);
                });
            });
        </script>

Note that this code makes a call to a Controller. It doesn’t have to be that way. I use it this way to perform server-side validations. The code would look like this:

    public ActionResult NovaLinhaDia()
    {
        return PartialView("_CondicoesPagamentoDia", new CondicaoPagamentoDiasViewModel());
    }

Making the POST form, you will see that CondicaoPagamentoDiass you will receive all the rows completed on the form there at Action of Controller.

  • Gypsy in my case he is not finding the Begincollectionitem, I need to do something in my Viewmodel?

  • You installed Begincollectionitem via command Install-Package BeginCollectionItem?

  • I just installed.

  • Now just follow the steps. Any questions can call me here, or open another question.

  • @Section Scripts { @{ Html.Renderpartial("_Validationmaskpartial"); do I put the partial in that space? with quotes? Or in the helper? }

  • No, the @section Scripts is only for the JS’s View.

Show 2 more comments

1

I believe you are doubtful in recovering the form data. Try the code below. Template:

  public ActionResult Gravar()
  {
    string[] chaves = Request.QueryString.AllKeys;
    Dictionary parametros = new Dictionary();
    foreach (string chave in chaves)
    {
      parametros[chave] = Request.QueryString[chave];
    }

    string nome = parametros["Nome"];
    string tipo = parametros["Tipo"];
    string dia2 = parametros["Dia1"];
    string dia1 = parametros["Dia2"];
    string diaN = parametros["DiaN"];

    // demais linhas de código.

    return View();
  }

Browser other questions tagged

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