Pass view bag value to view

Asked

Viewed 659 times

1

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();
}

In case BT will take the value in the bath table and Tosa and add another 10, and then will return the sum value in the viewbag. Total.

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>

value = "@Viewbag.Total" was supposed to receive the value of Viewbag.

  • What value is being received by value currently?

  • @LINQ then the editor field is not receiving the value of viewbag. ,this being empty.

  • @caiooliveira your "not receiving" means that the value comes 0 or the value comes null?

  • ata comes null kkk

  • @Kelvynrisso I saw that you already solved a question a little bit like here in the stack, I would like you to take a look at my question.

1 answer

1

Then the most correct would be to create a Viewmodel for this view, example:

public class CreateBanhoTosaViewModel
{
    public int? Total { get; set; }
}

Then use on your controller more or less like this:

public ActionResult Create()
{
    //aqui você seleciona o valor do total
    var viewModel = new CreateBanhoTosaViewModel { Total = 1 };

    return View(viewModel);
}

Your view will need to reference this model view using @model, she’ll stay like this:

@model App.Models.CreateBanhoTosaViewModel

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

This way you will be using the framework correctly.

Anyway if you prefer to continue using the @ViewBag, you would have to write the control in hand, sort of like this:

<input name="Total" id="Total" value="@ViewBag.Total" />

I do not recommend you use this option.

Browser other questions tagged

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