MVC 5 and EF 6 Putting Form from another view

Asked

Viewed 943 times

3

Keeps giving comment error null in this line:

ViewBag.PostId = new SelectList(db.Posts, "PostId", "Titulo", comentario.PostId);

Probably why you didn’t sing in the ModelState.IsValid.

I’m doing a project there from college. My project is a blog, something simple. What I need now is in the View of each Article put a Form below for the person to post the comments of that Article. How do I? Why would Submit be for the ComentarioController only that he’s in view article.

Form you are in View Post:

@model WebBlog.Models.Post
@{
    ViewBag.Title = "Post";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/Home.css" rel="stylesheet" />

<div class="jumbotron">
    <div class="post-title">@Html.DisplayFor(model => model.Titulo)</div>
    <div class="postmeta">Postado em 13/05/2014 | por @Html.DisplayFor(model => model.Autor.Nome)</div>
    <div class="entry">@Html.DisplayFor(model => model.Conteudo)</div>
</div>
<div class="jumbotron">
    <div class="post-title">Comentarios</div>
    @foreach (var item in Model.Comentarios)
    {
        <div class="postmeta">
            <div class="comment-author">
                <span class="fn">@Html.DisplayFor(modelitem => item.Autor)</span>
                <div class="commenta-meta">@Html.DisplayFor(modelitem => item.dataComentario)</div>
            </div>
        </div>
        <div class="entry">@Html.DisplayFor(modelitem => item.comenatrio)</div>
    }
</div>
<div class="jumbotron">
    <div class="post-title">Envie seu Comentario</div>
    @using (Html.BeginForm("Create", "Comentario", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            @Html.ValidationSummary(true)
            @Html.HiddenFor(model => model.PostId)

            <div class="form-group">
                <label class="control-label col-md-2" for="dataComentario">Data Comentario:</label>
                <div class="col-md-10">
                    <input type="text" name="dataComentario" class="disabled" disabled="disabled" id="dataComentario" value="@System.DateTime.Now.ToShortDateString()" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-2" for="Autor">Autor:</label>
                <div class="col-md-10">
                    <input type="text" name="Autor" id="Autor" />
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-md-2" for="Comentario">Comentario:</label>
                <div class="col-md-10">
                    <textarea class="control-label col-md-2" id="Comentario" name="Comentario"></textarea>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Comentar" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
</div>

Now the Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
    [Bind(Include="ComentarioId,PostId,dataComentario,Autor,comenatrio")] 
    Comentario comentario)
{
    if (ModelState.IsValid)
    {
        db.Comentarios.Add(comentario);
        db.SaveChanges();
        return RedirectToAction("Post", "Home", new {PostId = comentario.PostId});
    }

    ViewBag.PostId = new SelectList(db.Posts, "PostId", "Titulo", comentario.PostId);
    return View(comentario);
}

The error that occurs is that it does not enter this if (ModelStatte.IsValid) { ... }. Then when you go to the line ViewBag makes the mistake. I noticed that Model Comentario is not being instantiated.

1 answer

2


About the form pointing to a Controller and a Action specific:

You can specify where Submit will be pointed!

<form actiom="~/Comentario/Adicionar" method="post">
    ...
</form>

Or:

@Html.BeginForm("Adicionar", "Comentário", FormMethod.Post)
{
    ...
}

Or even:

<form action="" method="post" id="formComentario">
   ...
</form>

<script type="text/javascript">
    $(function () {
        $("#formComentario").submit(function () {
            $(this).attr("action", "/Comentario/Adicionar");
        });
    });
</script>

About the mistake in your Controller:

About the Controller error, let’s go to some details

  • You said the Model Comentario is not being instilled.

If you’re not really being insticed the value you should see in it when debugging is the null.
If it really is that, test put on your View typing, if it does not have:

// algo como
@model Models.Comentario
  • If it’s not null, but an unstable class with values default empty: 0 to int, void for string:

So it could be something I’m believing in. Which is this:
Your view is declared manually and I’m seeing in the fields Id s and name s as dataComentario and comentario. But I don’t think you should have left your class fields in the pattern lowerCamelCase. I believe you’re like:

public DateTime DataComentario { get; set; }
public string Comentario { get; set; }

So, check these items and return what you can find. About not being in the scope of if (ModelStatte.IsValid) { ... } It is exactly because your Model has not been insticed or not have all the fields matched with what is needed to validate it. As defined in your class annotations, or by your mapping Fluent.

The pattern of Framework MVC of ASP.NET is that the fields have exactly the same name as the class property for it to parse for you.

The idea of using the Helpers is so that the Razor treat it to you, like:

@Html.EditorFor(x => x.Comentario)

Will be generated:

<input type="text" id="Comentario" name="Comentario" />
  • 3

    See the code snippet from Create: if (Modelstate.Isvalid) { db.Comentarios.Add(comment); db.Savechanges(); Return Redirecttoaction("Post", "Home", new {Postid = comment.Postid}); } Viewbag.Postid = new Selectlist(db.Posts, "Postid", "Title", comment.Postid); Return View(comment); Why is this returning the error in Viewbag: Undefined object reference for an instance of an object.

  • I will edit the Question by placing the code snippet of my Form and my controller.

  • Okay. Thank you very much.

Browser other questions tagged

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