将视图中的值作为输入值传递到ASP.NET MVC中

时间:2014-05-20 23:22:47

标签: c# asp.net-mvc asp.net-mvc-4

我有一个调用子操作的视图:

@Html.Action("RenderPostMessage", "JobSurface")

控制器是这样的:

public ActionResult RenderPostMessage()
{
    PostMessageViewModel postMessageViewModel = new PostMessageViewModel();
    return PartialView("PostMessage", postMessageViewModel);
}

此调用的部分内容如下:

@model PostMessageViewModel

@{
    Html.EnableClientValidation(true);
    Html.EnableUnobtrusiveJavaScript(true);
}
@using (Html.BeginUmbracoForm<JobSurfaceController>("HandlePostMessage", new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)       

    <p>
        @Html.EditorFor(model => model.Message)
        @Html.ValidationMessageFor(model => model.Message)
    </p>

    <p>
        @Html.LabelFor(model => model.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
    </p>
    <p><button class="button">Post Message</button></p>
}

&#39>处理帖子消息&#39;控制器是这样的:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult HandlePostMessage(PostMessageViewModel model)
{
    // Some logic
}

我在视图中有一堆变量,我需要以某种方式传入表单(可能是隐藏的输入字段?)但是虽然我知道如何在部分上创建隐藏的输入,但我不知道如何使用视图中的值填充它们。

有人可以建议如何将值传递给控制器​​吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

@Html.Action有一个参数&#39; routeValues&#39;这是一个匿名对象。你可以在那里传递值。所以......从观点到行动:

@Html.Action("RenderPostMessage", routeValues:new{SurfaceType = "JobSurface", OtherValue = "Something", NewValue = "Something else"});

Action接受这些路由值作为方法参数:

    public ActionResult RenderPostMessage(string surfaceType, string otherValue, string newValue)
    {
        var viewModel = new PostMessageViewModel();
viewModel.SurfaceType = surfaceType;
viewModel.OtherValue = otherValue;
viewModel.NewValue = newValue;
        return PartialView("PostMessage", viewModel);
    }

完成!

答案 1 :(得分:1)

  

我在视图中有一堆变量,我需要以某种方式传入   到形式(可能是隐藏的输入字段?)

很简单,如果要使用值渲染隐藏的输入字段,请将其添加到视图中的ViewBag对象。

例如,如果要将变量的内容添加到表单中,则在视图中执行此操作:

ViewBag.Foo = "Some Value";

然后在cshtml文件中添加隐藏字段:

@Html.Hidden("Foo")

这样您就会收到表单中的值。

编辑:这是您的代码的外观。

public ActionResult RenderPostMessage()
{
    PostMessageViewModel postMessageViewModel = new PostMessageViewModel();

    // here you set as many values as you want to receive in the form post.
    ViewBag.SomeField = "Some Value";

    return PartialView("PostMessage", postMessageViewModel);
}

查看

@model PostMessageViewModel

@{
    Html.EnableClientValidation(true);
    Html.EnableUnobtrusiveJavaScript(true);
}
@using (Html.BeginUmbracoForm<JobSurfaceController>("HandlePostMessage", new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)       

    @Html.Hidden("SomeField")

    <p>
        @Html.EditorFor(model => model.Message)
        @Html.ValidationMessageFor(model => model.Message)
    </p>

    <p>
        @Html.LabelFor(model => model.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
    </p>
    <p><button class="button">Post Message</button></p>
}