How to send Partialview input to a controller?

Asked

Viewed 156 times

0

I tried to find something that would take away this doubt, but there’s nothing concrete for what I want.

I’m using Visual Studio 2015 and MVC 5 and Razor in my project.

I have a form (Create) with a Submit in a partial view and I have this partial view rendered in another view (it’s a post comments box).

I have also implemented the [Httppost] do Create() but when I click Submit to submit the comment he does not Post for my function [Httppost], how do I send the data to this method? I have the input parameter like this: Create (Formcollection Collection).

I know this question may seem trivial, but I’m still on a very initial face.

Partial view code:

@model shanuMVCUserRoles.CommentSet

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Adicione um comentário</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.MemberID)
    @Html.HiddenFor(model => model.PostID)

    <div class="form-group">
        @Html.LabelFor(model => model.Content, htmlAttributes: new {    @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Content, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Criar" class="btn btn-default" />
        </div>
    </div>
</div>
}

And controller:

    // GET: Comment/Create
    public ActionResult Create()
    {

        CommentSet newComment = new CommentSet();

        return PartialView(newComment);
    }

    // POST: Comment/Create
    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        CommentSet newComment = new CommentSet();

        BlogEntities db = new BlogEntities();

        int id = Convert.ToInt32(collection["MemberID"]);

        newComment.Content = collection["Content"];
        newComment.MemberID = Convert.ToInt32(collection["MemberID"]);
        newComment.MemberSet = db.MemberSet.Single(m => m.ID == id);
        newComment.PostID = Convert.ToInt32(collection["PostID"]);
        newComment.VotesDown = 0;
        newComment.VotesUp = 0;



        try
        {
            db.CommentSet.Add(newComment);
            db.SaveChanges();

            return RedirectToAction("Index"); /*AINDA NAO CONFIGUREI ISTO*/
        }
        catch
        {
            return View();
        }
    }

Code where I call the partialview:

<div class="col-xs-6">
            <h5>@item.Content</h5>
            <div class="list-group">
                @foreach (var comment in item.CommentSet)
                {
                    <a href="#" class="list-group-item">
                        <h4 class="list-group-item-heading">@comment.MemberSet.UserName</h4>
                        <p class="list-group-item-text">@comment.Content</p>
                    </a>
                }

                @Html.Partial("_AdicionarComentario", new CommentSet { PostID = item.ID })

            </div>

        </div>
  • If possible, post your code to further analyze your problem

  • One thing I noticed just now, you have the property PostID, but there is no input with the value of this property in your Partialview, add a @Html.HiddenFor(model => model.PostID)

  • I’ve corrected it. I’ve been researching and I’ve seen people who use Ajax to do something similar, will it be good for this case? (I didn’t want to learn everything at once, which is why I prefer to use only c# and Razor, but if necessary...)

  • I believe you don’t need to use Ajax. @using (Html.BeginForm("TuaAction", "TeuController"))

  • That solved my problem. I think I should put that in the answers, it seemed haha magic

  • How do you know you’re not calling the Create method? ?

Show 1 more comment

1 answer

1


The solution to your problem is to specify in your Form the action, being as follows @using (Html.BeginForm("TuaAction", "TeuController"))

But because you use Typed View, you can change your Create(FormCollection collection) for Create(CommentSet commentSet).

Being as follows

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CommentSet commentSet)
        {
            if (ModelState.IsValid)
            {
                db.CommentSet.Add(commentSet);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(commentSet);
        }

But its main problem is that the Create missing attribute [ValidateAntiForgeryToken], having this attribute in order to protect access to your application by fake Http requests, it ensures that the request comes only from your View using a kind of "key".

  • but what difference does it make to have Collectionform or Commentset? I can’t even get to the method [Httppost]

  • I completed the answer.

  • I still can’t send the comment to the database. A detail that may be useful: after doing Ubmit the page reloads, but if I refresh the page (F5) I get this: "To show this page, Firefox has to resend information that repeats previous actions (such as a search or confirmation of an order)."

  • Put the view code where you load this partial.

Browser other questions tagged

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