Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass model in MVC view

I want to pass model from form to controler and show others models in the same view. How can I do this? My main problem is: how to send into testAcc actionresult, model CommentModel, and show text in ViewData["Success"] ?

Here is my code:

    @model XYZ.Models._ideaDetailsWrapper
    @using XYZ.Tools   
<article>
    <h2>@Model.idea.Tilte</h2>

<table><tr><td>
<p>
    Author: <b>@UserTools.getUser(Model.idea.AuthorID).UserName</b><br />
    Add date: @Model.idea.AddDate<br />
    Category: @IdeasTools.getCategoryName(Model.idea.CategoryID)<br />
</p></td>
</tr></table>

<p><b>Content:</b><br />
    @Model.idea.Content</p>

<br /><br />

// HERE - ADD comment

    @using (Html.BeginForm("testAcc", "Ideas", FormMethod.Post))
    { 
            <h4>Add comment:</h4>

            @Html.LabelFor(m => m.addComment.Content)
            @Html.EditorFor(m => m.addComment.Content)<br />
        <input type="submit" value="SendEmails" />
    }

@ViewData["Success"]

wrapper:

public class _ideaDetailsWrapper 
{
    public Ideas idea { get; set; }
    public IEnumerable<IdeasComment> commentList { get; set; }
    public CommentModel addComment { get; set; }
}

Action method:

    [HttpPost]
    [Authorize]
    public ActionResult testAcc(CommentModel model)
    {

        CommentModel abs = model;

        ViewData["Success"] = "Working!";

        // ADD TO DATABASE, but model is null..
        return RedirectToAction("Details", "Ideas");
    }
like image 862
whoah Avatar asked Apr 20 '13 22:04

whoah


1 Answers

One way to do this is to use a Partial View.

Details.cshtml

@model XYZ.Models._ideaDetailsWrapper
...
// HERE - ADD Comment
<div id="comment-form">
@Html.Partial("_CommentForm", Model.addComment)
</div>

@Model.message
// add validation javascript to this view

_CommentForm.cshtml (Partial View)

@model XYX.Models.CommentModel
@{
    Layout = null;
}

@using (Html.BeginForm("testAcc", "Ideas", FormMethod.Post))
{ 
      @Html.ValidationSummary(true)
        <h4>Add comment:</h4>

        @Html.LabelFor(m => m.Content)
        @Html.EditorFor(m => m.Content)
        @Html.ValidationMessageFor(m => m.Content)<br />
    <input type="submit" value="SendEmails" />
}

The partial view is strongly typed and will submit the CommentModel

Action methods:

[HttpPost]
[Authorize]
public ActionResult testAcc(CommentModel model)
{
    string abs = model.Content;

    TempData["Message"] = "Working!";

    // ADD TO DATABASE
    return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
}

[HttpGet]
[Autorize]
public ActionResult Details(int id)
{
    var ideaModel = dbStore.GetIdea(id);  // however you do this

    var model = new _ideaDetailsWrapper {
        idea = ideaModel,
        addComment = new CommentModel(),
        message = TempData["Message"]
        ...
    };
    return View(model);
}

Use TempData to pass the message through redirect. You'll check if TempData["Message"] exists in the Details action when you first load the page directly before you use it.

Edit: For Validation just add the validation javascript to the Details view and the ValidationSummary to the partial view.

Edit 2: This method breaks down with validation and error handling. For this to work it needs AJAX to replace the form div without reloading the entire page.

You need to intercept the normal form submission and handle it yourself using AJAX

$("form").on("submit", function(event) {
    event.preventDefault();
    $.ajax({
        url: "/Ideas/testAcc",
        type: "POST",
        data: $("form").serialize()
    })
    .done(function(partialViewHtml) {
        $("#comment-form").html(partialViewHtml);
    });
});

Your action becomes

[HttpPost]
public ActioNResult testAcc(CommentModel model)
{
    if (ModelState.IsValid)
    {
        ...
        return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
    }
    return PartialView("_CommentForm", model);
}
like image 52
Jasen Avatar answered Oct 12 '22 13:10

Jasen