Ajax.BeginForm is duplicating when the model is not valid

时间:2015-07-31 19:25:59

标签: c# asp.net-mvc asp.net-mvc-partialview unobtrusive-javascript ajax.beginform

I am writing a PartialView Ajax.BeginForm. This partial is composed by a list of messages and a field to send a new message as showed in the figure below: enter image description here

the Partial has the following code:

Code that List the messages

@if (Model != null)
{

    <div class="chat-activity-list" id="listaMensagens">
    @foreach (Inspinia_MVC5.Models.PostComentarios comentario in Model.Where(c => c.Usuarios.UsuEmail.Contains(User.Identity.Name) || (c.Usuarios.UsuId == c.Post.UsuId && (c.UsuariosDestinatario != null && c.UsuariosDestinatario.UsuEmail.Contains(User.Identity.Name)))).ToList())
    {
        <div class="chat-element @(comentario.UsuId == comentario.Post.UsuId ? "right" : "")">
            <a class="@(comentario.UsuId == comentario.Post.UsuId ? "pull-right" : "pull-left")" href="#">
                <img src="/Servicili/Images/a2.jpg" class="img-circle" alt="image">
            </a>
            <div class="media-body @(comentario.UsuId == comentario.Post.UsuId ? "text-right" : "")">
                <small class="@(comentario.UsuId == comentario.Post.UsuId ? "pull-left" : "pull-right") text-navy">@Inspinia_MVC5.Helpers.DateHelper.getTempo(comentario.PosComDataEnvio)</small>
                <i class="fa fa-star @(comentario.UsuId == comentario.Post.UsuId ? "text-success" : "text-warning") "></i>
                <strong>@comentario.Usuarios.Clientes.CliNome</strong>
                <p class="m-b-xs">
                    @comentario.PosComComentario
                </p>
                <small class="text-muted">@comentario.PosComDataEnvio</small>
            </div>
        </div>
    }
    </div>
}
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

code of the Form to send a new message

<div class="chat-form">
    @using (Ajax.BeginForm("EnviarMensagem", "OrcamentosServicos", new AjaxOptions() { UpdateTargetId = "listaMensagens", InsertionMode = InsertionMode.InsertAfter }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
        //@Html.HiddenFor(m => m.FirstOrDefault().Post.PostOrcamentoServico.FirstOrDefault().PosOrcSerId)
        <div class="form-group">
            @Html.TextArea("PosComComentario", new { @placeholder = "Digite uma mensagem...", @class = "form-control" })
        </div>
        <div class="text-right">
            <button type="submit" class="btn btn-sm btn-success m-t-n-xs">Enviar mensagem</button>
        </div>
    }
</div>

In my controller I have the following methods:

Return the PartialView that will render those comments (PostComentarios)

public PartialViewResult EnviarMensagem(HashSet<PostComentarios> lComentarios)
{
    return PartialView(lComentarios); 
}

For the [Post] method, I have the following code:

[HttpPost]
public PartialViewResult EnviarMensagem(PostComentarios comentario/)
{
   if (string.IsNullOrEmpty(comentario.PosComComentario))
     ModelState.AddModelError("PosComComeentario", "Informe um texto para enviar a mensagem.");
   if (ModelState.IsValid)
     return PartialView("ListaMensagens");
   else
     return PartialView();
}

And I have another Partial view that is used only to render a new message called ListaMensagens...

My problem is that, when I try to use Validation, the system is duplicating the main form as showed below:

enter image description here

Can somebody tell me what I am doing wrong?

1 个答案:

答案 0 :(得分:0)

From what I see, you are using insertion mode InsertionMode.InsertAfter, which means the results from the Action method will be inserted after the existing data in the form.

if (ModelState.IsValid)
    return PartialView("ListaMensagens");
else
    return PartialView();

In the event that your model is not valid, you are returning the whole Partial View, which is inserted after the existing elements in your form. This results in placing whole additional copy of the partial view after your existing one, duplicating everything in it including the textbox and button.

相关问题