5
I have a Dropdown that lists the categories of my system, but when I submit the form without choosing a category, it gives a server error saying that the Value cannot be null. I put a validation with Validationmessagefor, but it still doesn’t work and error. If you take my Dropdown it validates the other fields, including another Dropdown q I have in the same form, plus it does not use Viewbag. If anyone can help me..
Segue Controller:
public ActionResult Adicionar()
{
var cookie = DinheiroControlado.Repositorios.RepositoriosUsuarios.VerificaSeOUsuarioEstaLogado();
ViewBag.teste = cookie.IDUsuario;
ViewBag.Categoriaslist = db.Categorias.ToList();
var lista = new List<Categorias>();
lista = db.Categorias.ToList();
return View();
}
[HttpPost]
public ActionResult Adicionar(Movimentacoes movimentacoes)
{
var cookie = DinheiroControlado.Repositorios.RepositoriosUsuarios.VerificaSeOUsuarioEstaLogado();
movimentacoes.IDUsuario = cookie.IDUsuario;
var contador = movimentacoes.Parcelas;
if (contador > 0)
{
for (int i = 0; i < contador; i++)
{
if (ModelState.IsValid)
{
if (i == 0)
{
db.Movimentacoes.Add(movimentacoes);
db.SaveChanges();
}
else
{
var data = movimentacoes.Data.Day + "/" + (movimentacoes.Data.Month + 1) + "/" + movimentacoes.Data.Year;
movimentacoes.Data = Convert.ToDateTime(data);
movimentacoes.Parcelas = movimentacoes.Parcelas - 1;
db.Movimentacoes.Add(movimentacoes);
db.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
else
{
if (ModelState.IsValid)
{
db.Movimentacoes.Add(movimentacoes);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movimentacoes);
}
return View(movimentacoes);
}
Segue View:
@model DinheiroControlado.Models.Movimentacoes
@{
ViewBag.Title = "Adicionar";
Layout = "~/Views/Layout2.cshtml";
}
<section id="title" class="emerald">
<div class="container">
<div class="row">
<div class="col-sm-6">
<h1>Movimentações</h1>
<p>Lance suas despesas e suas receitas de maneira fácil e rápida!</p>
</div>
<div class="col-sm-6">
<ul class="breadcrumb pull-right">
<li><a href="@Url.Action("Index","Home")">Home</a></li>
<li class="active">Movimentações</li>
</ul>
</div>
</div>
</div>
</section><!--/#title-->
<section>
<div class="container">
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset class="registration-form">
<div class="form-group">
<legend>Movimentacoes</legend>
@Html.RadioButtonFor(x => x.ReceitaDespesa, "DESPESA") Despesa<br />
@Html.RadioButtonFor(x => x.ReceitaDespesa, "RECEITA") Receita<br />
@Html.ValidationMessageFor(model => model.ReceitaDespesa)
</div>
<div class="form-group">
@Html.TextBoxFor(model => model.Data, "", new { @class = "form-control", @placeholder = "Data", @id = "datepicker"})
@Html.ValidationMessageFor(model => model.Data)
</div>
<div class="form-group">
@Html.TextBoxFor(model => model.Descricao, "", new { @class = "form-control", @placeholder = "Descrição" })
@Html.ValidationMessageFor(model => model.Descricao)
</div>
<div class="form-group">
@Html.TextBoxFor(model => model.Valor, "{0:C2}", new { @class = "form-control", @placeholder = "Valor"})
@Html.ValidationMessageFor(model => model.Valor)
</div>
<div class="form-group">
@Html.TextBoxFor(model => model.Parcelas, "", new { @class = "form-control", @placeholder = "Parcelas", @type = "number", @mim = "0", @max = "400" })
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.Mensal, new List<SelectListItem> { new SelectListItem { Value = "0" , Text = "SIM" }, new SelectListItem { Value = "1" , Text = "NÃO" } }, "Mensal", new { @class="form-control"} )
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.IDCategoria, new SelectList(ViewBag.Categoriaslist, "IDCategoria", "SubCategoria"), "Categoria", htmlAttributes: new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.IDCategoria)
</div>
<p>
<input type="submit" value="Cadastrar" class="btn btn-primary"/>
</p>
<div>
<a href="@Url.Action("Index", "Movimentacao")" class="btn btn-primary">Retornar</a>
</div>
</fieldset>
}
</div>
Follows Error:
Erro de Servidor no Aplicativo '/'.
Valor não pode ser nulo.
Nome do parâmetro: items
Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: System.ArgumentNullException: Valor não pode ser nulo.
Nome do parâmetro: items
Erro de Origem:
Linha 67:
Linha 68: <div class="form-group">
Linha 69: @Html.DropDownListFor(model => model.IDCategoria, new SelectList(ViewBag.Categoriaslist, "IDCategoria", "SubCategoria"), "Categoria", htmlAttributes: new { @class = "form-control"})
Linha 70: @Html.ValidationMessageFor(model => model.IDCategoria)
Linha 71: </div>
Arquivo de Origem: c:\TCC\C#\DinheiroControlado\DinheiroControlado\Views\Movimentacao\Adicionar.cshtml Linha: 69
Rastreamento de Pilha:
[ArgumentNullException: Valor não pode ser nulo.
Nome do parâmetro: items]
System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues) +102
CallSite.Target(Closure , CallSite , Type , Object , String , String ) +155
System.Dynamic.UpdateDelegates.UpdateAndExecute4(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) +738
CallSite.Target(Closure , CallSite , Type , Object , String , String ) +309
ASP._Page_Views_Movimentacao_Adicionar_cshtml.Execute() in c:\TCC\C#\DinheiroControlado\DinheiroControlado\Views\Movimentacao\Adicionar.cshtml:69
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9723757
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It may be that the modelState is not valid and this returns to view, without filling the Viewbag.Categoriaslist according to your code. Try returning Viewbag.Categoriaslist populated again if Modelstate is not valid.
– Janderson Thomaz
Janderson, it worked using your alternative, solved my problem man, thank you so much! Hug.
– Rodrigo Santos
Blz, I put as an answer you mark as right.
– Janderson Thomaz