MVC 5 and EF 6 Put form from another view

Keeps giving the comment error null in this line:

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

Probably why you didn't enter 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 to put a form underneath for the person to post the comments of that Article. How do I do it? Why would submit be for the ComentarioController only that it is in the View of the article.

Form that this is 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 it goes to the line of ViewBag it gives the error. I noticed that model Comentario is not being instantiated.

Author: stderr, 2014-05-18

1 answers

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

You can specify where the submit will be pointed to!

<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 error in your Controller :

About the error in the Controller, let's go to some details

  • you said the Model Comentario it is not being instantiated.

If it really isn't being instantiated the value you should see in it when debugging is the null.
If that really is the case, try typing in your view if you don't have:

// algo como
@model Models.Comentario
  • if not null, but rather an instantiated class and with the values default of empty: 0 to int, empty for string:

So it might be something I'm believing in. Which is as follows:
Your view is declared manually and I am seeing in the fields the Ids e names like dataComentario and comentario. But I don't think you should have left your class fields in the default lowerCamelCase. I believe it is like:

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

Then, check these items and return what you can find. About not being in the scope of if (ModelStatte.IsValid) { ... } is exactly because your Model hasn't been instantiated or doesn't have all of the acotdo fields with what is needed to validate it. As defined in your class annotations, or by your mapping Fluent .

The default of the MVC framework of the ASP.NET is that the fields have exactly the same name as the class property for it to parser for you.

The idea of using Helpers it is for the Razor treat this to you, like:

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

Will be generated:

<input type="text" id="Comentario" name="Comentario" />
 2
Author: , 2014-05-19 13:09:23