0

I'm trying to pass value from a view bag to the view create.

Controller

public ActionResult Create()
{
    ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");


    if (ViewBag.BanhoTosaId.SelectedValue != null)
    {
        BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
        decimal valorSoma = BT.Valor + 10;
        ViewBag.Total = valorSoma;
    }
    else
    {
        ViewBag.Total = 0;
    }

    return View();
}

view

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

In case BT will get the value in the BanhoTosa table and add 10, and then will return the value of the sum in the viewbag.Total.

But in view the @Html.EditorFor is receiving nothing

How can i do for the editorfor receive the value from the viewbag.total?

Thank's Guy's

Leonardo Henriques
  • 784
  • 1
  • 7
  • 22
lazernet
  • 9
  • 1
  • 1
    Hello. You should really be using a strongly typed model for you views data. have a read of this.. https://stackoverflow.com/questions/11262034/mvc-viewbag-best-practice – Wheels73 Mar 08 '18 at 14:09
  • 1
    `@Html.EditorFor(model => model.Total, new { htmlAttributes = new { @class = "form-control", value = "@ViewBag.Total" } }) ` makes very little sense. The whole point of having a model is that `model.Total` would contain the value, there's no reason to side-load it from the ViewBag. I suggest you take the introductory MVC tutorial from Microsoft, because you appear to be totally missing the point of how MVC is designed to work. – ADyson Mar 08 '18 at 15:09

0 Answers0