Get value from a view field in a controller

Asked

Viewed 638 times

1

From the answers here, I couldn’t catch it. I have this view

    @{
    ViewBag.Title = "ExcelFinancing";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <style>
        .embaixo {
            position: absolute;
            left: 0;
            bottom: 20%;
            width: auto;
            bottom: auto;
            top: 50%;
            margin: 10%,10%,10%,10%;
        }
    </style>
</head>
<body>
    <div class="row">
        <div class="col-lg-12">
            <h3 class="page-header fa-align-center">@ViewBag.TitlePage</h3>
        </div>
    </div>

    @*<div class="panel panel-default">*@

    <div class="form-group">

        <div class="col-md-1">
            @Html.Label("De")
        </div>

        <div class="col-md-3">
            @Html.EditorFor(model => model.datefinancing, new { htmlAttributes = new { @class = "form-control", ID = "dataIni" } })
            @Html.ValidationMessageFor(model => model.datefinancing, "", new { @class = "text-danger" })
        </div>

        <div class="col-md-1">
            @Html.Label("Até")
        </div>
        <div class="col-md-3">
            @Html.EditorFor(model => model.datefinancing, new { htmlAttributes = new { @class = "form-control", ID = "dataFim" } })
            @Html.ValidationMessageFor(model => model.datefinancing, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="row">
        <div class="input-field col s3">
            <div>

                <p>
                    @{string Todos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Todos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Todos", new { id = Todos, name = "imp_tx_tipo", value = "Todos", @class = "with-gap" })
                    <label for="Todos">Todos</label>
                </p>
                <p>
                    @{string Ativos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Ativos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Ativos", new { id = Ativos, name = "imp_tx_tipo", value = "Ativos", @class = "with-gap" })
                    <label for="Ativos">Ativos</label>
                </p>
                <p>
                    @{string Inativos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Inativos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Inativos", new { id = Inativos, name = "imp_tx_tipo", value = "Ativos", @class = "with-gap" })
                    <label for="Inativos">Inativos</label>
                </p>
                @Html.ValidationMessageFor(model => model.statussolicitation, "", new { @class = "red-text text-darken-2" })

            </div>
        </div>
    </div>

        @using (Html.BeginForm("geraExcel1", "FinancingReport", FormMethod.Post))
        {
            <div class="input-group">
                <div class="input-group-btn">
                    <input type="submit" value="Gerar Relatório" class="btn btn-primary" />
                </div>
            </div>
        }

</body>
</html>

This is my controller

[HttpPost]
    public ActionResult geraExcel1()
    {
        var context = new SyngentaBenefitsEntities();
        var model = new SolicitationViewModel();

        //var teste = dataFim;

        geraExcel();
        ViewBag.TitlePage = "Relatório de Financiamento";
        return null; 
    }

    [HttpPost]
    public ActionResult geraExcel()
    {  
        List<vwFinancingReportViewModel> lista = new List<vwFinancingReportViewModel>();
        lista = dadosPlanilha();

        StringBuilder sb = new StringBuilder();
        sb.Append("Status;Nro.Pessoal;Nome Completo;Grade;Nro.Solicitação;Data Financiamento;" + 
            "Ano Fabric.;Modelo;Chassi;Valor Bem;Valor Financiado;Status Solicitação;Status Pagamento;" +
            "Valor Parcela;Juros;ReembolsoKM;Reembolso Depreciação\r\n");
        foreach(var item in lista)
        {
            sb.Append(item.employeestatus.ToString() + ";" + item.employeeid.ToString() + ";" + item.fullname.ToString() + ";" +
                      item.grade.ToString() + ";" + item.solicitationid.ToString() + ";" + item.datefinancing.ToString() + ";" +
                      item.manufacturer.ToString() + ";" + item.model.ToString() + ";" + item.chassi.ToString() + ";" +
                      item.valueproperty.ToString() + ";" + item.valuegranted.ToString() + ";" + item.statussolicitation.ToString() + ";" +
                      item.paymentstatus.ToString() + ";" + item.valuepayment.ToString() + ";" +
                      item.valueinterest.ToString() + ";" + item.refundkm.ToString() + ";" +
                      item.refund.ToString() + "\r\n");

        }
        //sb.Append("Eduardo;11111\r\n");
        //sb.Append("Coutinho;22222\r\n");

        HttpContext.Response.Clear();
        HttpContext.Response.AddHeader("content-disposition", string.Format("attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + "ReportFinanciamentoRH.csv"));

        HttpContext.Response.ContentType = "application/CSV";
        HttpContext.Response.ContentEncoding = System.Text.Encoding.Default;

        HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        HttpContext.Response.Write(sb.ToString());

        HttpContext.Response.End();

        return null;
    }

In the view I have a Datetime field, where it would be a filter for my sql, which would be Datainicio and Datafim. It turns out I am not knowing how to send these values to the controller, so I can use them in my query.

  • you can pass the value by Viewbag.Nomedavariable or By Model

  • @Marcosbrinner, but from View to Controller using Viewbag? I thought only the opposite was possible. I have a form and need to get its value in my controller

  • The yes now understood your question so you are using POST or GET to send the data ?:

  • You can go through Model when posting, or via ajax...

  • Just one question, I only need the values of two dates to feed a method(parameters). Do I have to submit the form? I know it’s basic, but I have this question.

  • yes, if these values are coming from the client-side you need some kind of uploads to the server, you can also go through the url to which the view loads

  • site type.com/controller/action? Datafim=18/06/2069

  • Ok, my action is Httppost and the Submit button takes care of sending the form. But as I do now, like, var test = ????? how do I load the var test? That’s the question. That way it won’t: var test = dataFim.Value; just a hypothetical example.

  • @Marcosbrinner, how I pass these values url when loading the view?

  • The question is not clear, please do a better search on the subject and format your question better (example: add the View to better understand how the page post is being done, update the code with Httppost in Action, etc...) so that we can help you out.

  • Have you tried to put everything inside "@using(Html" and pass your model parameter in the post method?

  • @Lucasriechelmannramos, I didn’t try to do that, to tell you the truth, I didn’t even think about it.

  • In none of the actions are you expecting any value?

  • @Lucasriechelmannramos, you were right. Renan, thanks for the "ear tug". If Lucas responds, I mark the answer.

  • @pnet then update the question code to make sense with the answer

Show 10 more comments

1 answer

2


Puts your whole form inside

@using (Html.BeginForm("geraExcel1", "FinancingReport", FormMethod.Post))

and uses the model to pass as a parameter in the post method

public ActionResult geraExcel1(Model model)
{
    ....
}

Browser other questions tagged

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