制作一个viewmodel而不是viewbag

时间:2018-03-12 17:18:01

标签: asp.net-mvc razor

如何创建视图模型以计算来自banhotosaid + transpote Id的值,而不是返回视图的总数。

// GET: AgendaBTs/Create
        public ActionResult Create(int id, int pet)
        {

            ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
            ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome", id);
            ViewBag.PetId = new SelectList(db.Pets, "PetId", "PetNome", pet);
            ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");

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

            return View();

我希望你们能帮帮我。

感谢的

1 个答案:

答案 0 :(得分:-1)

您如何填充下拉列表?

@Html.DropDownList("TransporteId", null, htmlAttributes: new { @class = "form-control" })

您正在将null传递给数据源。您应该传递有效的数据源,例如

@Html.DropDownList("TransporteId", (IEnumerable<SelectListItem>)ViewBag.BanhoTosaId,null, new { @class = "form-control" })

您似乎正在将值传递给使其转到else语句的操作:

 else
 {
   ViewBag.Total = 0;
 }

这就是它被设置为零的原因。所以你可以调试它并显示传递给动作的参数。

同样用这个替换你的if条件并更正你的代码,因为组合的选择应作为参数传递给你的action方法:

if (ViewBag.BanhoTosaId != null && ViewBag.SelectedValue != null)
{
  //you cannot pass the whole list to the Find Method, you should pass a valid integer or key 
  // BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
  BanhoTosa BT = db.BanhoTosas.Find(id);
  //Transporte TS = db.Transportes.Find(ViewBag.TransporteId);
   BanhoTosa BT = db.BanhoTosas.Find(pet);   
}