Error after performing an action redirect to a page

6

I think I'm going wrong with the code below, it should save the Client and redirect to the Client / Index page, but after saving it stays on the same page, using Debug it passes in the Client / Index (Action and View) , but does not open the page

 public ActionResult Cadastro(Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            if (IsCpf(cliente.CPF).Equals(true))
            {
                db.Cliente.Add(cliente);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
                ViewBag.Mensagem = "CPF Inválido"; 
        }

        ViewBag.Estados = new SelectList(SelecionarEstados(), "Value", "Text");
        return View(cliente);

    }

public ActionResult Index()
    {
        return View(db.Cliente.Where(s => s.Ativo == true).ToList());
    }

My View Index Note: Using Debug it passes in the ACTION Index, then passes in the View Index, just does not render.

@model IEnumerable<SistemaComercial.Models.Cliente>

@{
ViewBag.Title = "Clientes";
<link href="~/Content/Style.css" rel="stylesheet" />
@* ----- Boostrap ----- *@
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>}<ulclass="nav nav-pills">
<li role="presentation" class="active"><a href=''>Home</a></li>
<li role="presentation"><a href='http://localhost:63729/Cliente/Index'>Cliente</a></li>
<li role="presentation"><a href='http://localhost:63729/Entrada/Index'>Entrada</a></li>
<li role="presentation"><a href='http://localhost:63729/Fornecedor/Index'>Fornecedor</a></li>
<li role="presentation"><a href='http://localhost:63729/Produto/Index'>Produto</a></li>
<li role="presentation"><a href='http://localhost:63729/Usuario/Index'>Usuário</a></li>
<li role="presentation"><a href='http://localhost:63729/Gerencial/Index'>Relatórios</a></li>
<li role="presentation"><a href="http://localhost:63729/Venda/Index">Venda</a></li>
</ul>
<h2 class="text-primary">Listagem de Clientes</h2>
<button class="btn btn-link" formmethod="get" onclick="location.href='@Url.Action("Cadastro", "Cliente")'">Cadastrar Novo Cliente</button>
<table class="table table-striped table-responsive">
<tr>
    <th>
        Código
    </th>
    <th>
        CPF
    </th>
    <th>
        Nome Completo
    </th>
    <th>
        Data de Nascimento
    </th>       
    <th>
        Opções
    </th>
</tr>

@foreach (var clientes in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => clientes.Codigo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => clientes.CPF)
        </td>
        <td>
            @Html.DisplayFor(modelItem => clientes.NomeCompleto)
        </td>
        <td>
            @Html.DisplayFor(modelItem => clientes.DataNascimento)
        </td>        

        <td>
            <button class="btn btn-default details" data-id="@clientes.Codigo"><i class="glyphicon glyphicon-file"></i></button>
            <button class="btn btn-danger delete" data-id="@clientes.Codigo"><i class="glyphicon glyphicon-trash"></i></button>
            <button class="btn btn-primary edit" data-id="@clientes.Codigo"><i class="glyphicon glyphicon-edit"></i></button>
        <td>
    </tr>
}
</table>

<div class="modal" id="modal">

</div>

<script src="~/Scripts/Own/ScriptsModal.js"></script>

<script src="~/Scripts/bootstrap.min.js"></script>

@section Scripts{
@* ----- Jquery ----- *@
<script src="~/Scripts/jquery-2.1.4.intellisense.js"></script>
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
@* ----- Bootstrap ----- *@


}

My View Registration

@model SistemaComercial.Models.Cliente

@{
ViewBag.Title = "Cadastro";
Layout = "~/Views/Shared/MasterPageCadastro.cshtml";
<script src="~/Scripts/jquery.maskedinput.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>}<h2class="text-primary text-center">Cadastro de Cliente</h2>

 @using (Html.BeginForm())
 {
 @Html.ValidationSummary(true)

 <fieldset class="scheduler-border">
    <legend class="scheduler-border"></legend>
    <div style="padding:20px;">
        <div class="editor-label">
            CPF
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CPF)
            @Html.ValidationMessageFor(model => model.CPF)
        </div><br />

        <div class="editor-label">
            Nome Completo
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NomeCompleto, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.NomeCompleto)
        </div><br />

        <div class="editor-label">
            Data de Nascimento
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DataNascimento)
            @Html.ValidationMessageFor(model => model.DataNascimento)
        </div><br />
        <div class="editor-label">
            CEP
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CEP)
            @Html.ValidationMessageFor(model => model.CEP)
        </div><br />
        <div class="editor-label">
            Logradouro
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Logradouro)
            @Html.ValidationMessageFor(model => model.Logradouro)
        </div> <br />

        <div class="editor-label">
            Numero
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Numero)
            @Html.ValidationMessageFor(model => model.Numero)
        </div><br />

        <div class="editor-label">
            Bairro
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Bairro)
            @Html.ValidationMessageFor(model => model.Bairro)
        </div><br />

        <div class="editor-label">
            Cidade
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cidade)
            @Html.ValidationMessageFor(model => model.Cidade)
        </div><br />

        <div class="editor-label">
            Estado
        </div>
        <div class="editor-field">
            @Html.DropDownList("Estados")

        </div><br />

        <br />
        <button class="btn btn-default" onclick="location.href='@Url.Action("Index","Cliente")'">Cancelar</button>
        <input type="button" class="btn btn-success" value="Salvar (F5)" id="AjaxPost" />
        <br />
        <div id="content">

        </div>
    </div>
</fieldset>
}

@*<script>
jQuery(function ($) {
    $(".DataNascimento").mask("99/99/9999", { placeholder: "dd/mm/yyyy" });
    $("#CPF").mask("999.999.999-99");
    $("#CEP").mask("99.999-999");
 });
 </script>*@



<script>
$(document).ready(function () {

    $("#AjaxPost").click(function () {

        var dataObject = {  
            Logradouro: $("#Logradouro").val(),
            Numero: $("#Numero").val(),
            Bairro: $("#Bairro").val(),
            Cidade: $("#Cidade").val(),
            Estado: $("#Estados").val(),
            CEP: $("#CEP").val(),
            CPF: $("#CPF").val(),
            Ativo: true,
            NomeCompleto: $("#NomeCompleto").val(),
            DataNascimento: $("#DataNascimento").val()
        };

        $.ajax({
            url: "@Url.Action("Cadastro","Cliente")",
            type: "GET",
            data: dataObject,
            dataType: "json",
        });

    });
});

</script>
    
asked by anonymous 25.11.2015 / 12:32

1 answer

4

I do not see anything "wrong" in your code to not work, other than this try in your Action Index. If as you said, you are saving in the bank and redirecting, it might be calling catch in your Action.

I'd recommend some improvements to your code, which are:

Use Data Annotations on your properties to certify data, other options, thus becoming your Model Client.

[Required(ErrorMessage = "Campo Obrigatório")]
public string CPF { get; set; }

In your controller, you check only whether it is valid or not. You do not need this if else you added, so:

public ActionResult Cadastro( Cliente cliente)
{
    if (ModelState.IsValid)
    {
        db.Clientes.Add(cliente);
        db.SaveChanges();
        return RedirectToAction("Index");
        //Se for controller diferente, mude para isso: return RedirectToAction("Index","Cliente"); Lembrando de ter certeza que existe a Action Index no Controller Cliente.(Tem que ser escrito corretamente)
    }

    ViewBag.Estados = new SelectList(SelecionarEstados(), "Value", "Text");
    return View(cliente);
}

And in your Action Index, there is no need to use try catch , you simply return the data to View .

public ActionResult Index()
{
   return View(db.Cliente.Where(s => s.Ativo).ToList());
}

If db.Cliente.Where(s => s.Ativo).ToList()) and you are using some property, just check on your view if the list is null or not, like this:

@if(Model != null){
   //Coloque aqui o que precisar
}

EDITION

You are not using form to save the data, so RedirectToAction() will not work at all. If you really want to use ajax , you should go to view in the success event of ajax . To do this, change your action to verify that the request is coming from a Ajax request or not, like this:

 if (ModelState.IsValid)
{
    db.Clientes.Add(cliente);
    db.SaveChanges();
    //Se não for via ajax ele direciona para a action
      if (Request.IsAjaxRequest())
     {
         return Json(new { success = true }, JsonRequestBehavior.AllowGet);
     }
     return RedirectToAction("Index"); Lembrando de ter certeza que existe a Action Index no Controller Cliente.(Tem que ser escrito corretamente)
}

And your ajax code changes to direct you to the specific page, like this:

  $.ajax({
            url: "@Url.Action("Cadastro","Cliente")",
            type: "GET",
            data: dataObject,
            dataType: "json",
             success: function (response) {
                location.href = '@Url.Action("Index","Cliente")'; //Sua Action aqui
            }
        });

Remembering that in this way you lose many qualities of , such as validations for example. I advise you to use form normally, since you want to redirect the page. To do this, simply change your button to perform the submit, which looks like this:

 <input type="button" class="btn btn-success" value="Salvar (F5)" id="AjaxPost" />

For this:

 <input type="submit" class="btn btn-success" value="Salvar (F5)" />

Once you've done this, you will no longer need the Ajax code to save the data.

  

Remembering that Microsoft has the Ajax.BeginForm () to work with Ajax in MVC.

    
25.11.2015 / 14:30