如何在MVC视图中传递模型 [英] How to pass model in MVC view

查看:89
本文介绍了如何在MVC视图中传递模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将模型从表单传递给控制者,并在同一视图中显示其他模型.我怎样才能做到这一点?我的主要问题是:如何发送到testAcc动作结果,对CommentModel模型进行建模并在ViewData["Success"]中显示文本?

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"] ?

这是我的代码:

    @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"]

包装器:

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

操作方法:

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

        CommentModel abs = model;

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

        // ADD TO DATABASE, but model is null..
        return RedirectToAction("Details", "Ideas");
    }

推荐答案

一种方法是使用部分视图.

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 (部分视图)

@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" />
}

部分视图具有强类型,将提交CommentModel

The partial view is strongly typed and will submit the CommentModel

操作方法:

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

使用TempData通过重定向传递消息.当您第一次直接在使用页面之前加载页面时,将检查Details操作中是否存在TempData["Message"].

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.

对于验证,只需将验证javascript添加到详细信息"视图中,然后将ValidationSummary添加到部分视图中.

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

.此方法因验证和错误处理而失败.为此,需要AJAX替换div表单,而无需重新加载整个页面.

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.

您需要拦截常规表单提交并使用AJAX自己处理

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

您的动作变为

[HttpPost]
public ActioNResult testAcc(CommentModel model)
{
    if (ModelState.IsValid)
    {
        ...
        return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
    }
    return PartialView("_CommentForm", model);
}

这篇关于如何在MVC视图中传递模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆