Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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");
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...