Error after performing an action redirect to a page

Asked

Viewed 671 times

6

I believe I am going wrong the code below, it should after saving the Client and redirect to Client/Index page, but after saving is on the same page, using Debug it passes in 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 the Debug he passes in the ACTION Index, Then passes on View Index, runs the foreach normal, just 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>
}

<ul class="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 Register

@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>
}
 <h2 class="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>
  • Could you post your Index action? In the bank the Customer is saved? It actually calls the return RedirectToAction("Index", "Cliente");

  • I updated the question... Yes is saved.

  • Is the Register action in the same controller as your index? If so, try to replace the Return Redirecttoaction("Index", "Client"); By Return Index();

  • I’ve tried, but it’s still on the same page.

1 answer

3


I see nothing "wrong" in your code not to work, other than that try in its Action Index. If like you said, you’re saving in the bank and redirecting, it may be that this one is calling the catch in his Action.

I advise some improvements to your code, which are:

Utilize Data Annotations in its properties to certify the data, among other options, thus getting its Client Model.

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

In your controller, you only check whether it’s valid or not. You don’t need this if else that you added, getting like this:

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 the try catch, you simply return the data to the View.

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

Case db.Cliente.Where(s => s.Ativo).ToList()) and you’re using some property, just check in your view if the list is null or not, in this way:

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

EDITION

You are not using the form to save the data, then the RedirectToAction() will not work anyway. If you really want to use ajax, you must go to the view at the event Success of ajax. For this, change your action to check if the request is coming by a request Ajax or not, in this way:

 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 code ajax you change to direct to the specific page in this way:

  $.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 the , such as validations for example. I advise you to use form normally, since you want to redirect the page. For this, just change your button to perform the Submit, which is so:

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

For that reason:

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

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

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

  • I updated my question, with your suggestions, but it still doesn’t work.

  • @J.C.Galhardi could add his view Register?

  • I updated the question.

  • @J.C.Galhardi The Register view. Which goes into the action public ActionResult Cadastro( Cliente cliente)

  • @J.C.Galhardi I edited the answer, see if it fits now

  • From the looks of it, you’re not falling for Success ajax

  • How did I use the Html.Beginform.() even, now it’s working.

  • @J.C.Galhardi It was my fault. I edited the answer again, see if it meets you now

Show 3 more comments

Browser other questions tagged

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