从Controller中获取模型中的值

Nun*_*iro 1 asp.net-mvc asp.net-mvc-4

我从ASP.NET MVC 4开始,我有一个问题.

我有这个代码来向Model中的属性添加数据.

    public void SetModelValues()
    {
        var modelObj = new MyModel();
        modelObj.name="MyName";
        modelObj.email="someone@mymail.com";
        modelObj.company="MyCompany";
        modelObj.message="Some text here";
    }
Run Code Online (Sandbox Code Playgroud)

我如何从另一个行动中得到这个价值观?

谢谢,抱歉"新生":)

Sin*_*tic 7

我想帮助完成纳西尔的回答.他概述的是完全正确的.但是要回答您关于如何从另一个操作访问这些值的任务,该视图模型必须在下一个回发时传递回该控制器.因此,例如,您可以在一个动作中创建并保存视图模型,并将其传递给视图.MVC通过使用您的值创建控件,将数据传递回下一个回发中的表单.如果使用视图模型中的值,它们将丢失,因此要么使用这些值渲染控件:

@Html.TextBoxFor(m => m.MyProperty); 
Run Code Online (Sandbox Code Playgroud)

或者如果你想确保它在下一个回发中传递但是没有用于显示它,只需创建隐藏字段,以便它仍然在源中呈现,以便它可以传递回下一步行动:

@Html.HiddenFor(m => m.MyProperty);
Run Code Online (Sandbox Code Playgroud)

所以当你发回这个表格时会发生什么,它将作为表格数据(键值对)发送回通过提交表格调用的控制器动作.MVC将尝试将其反序列化为一个Action参数类型(因此请确保其中一个类型与ViewModel的类型相同).通过这样做,信息将在该操作中可用.

再详细说明一下

public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

// Index.cshtml - bound to MyViewModel
// This will render a text box that will read "Property 1". It will also render a hidden field 
// containing "Property 2" but will not be displayed on the page. When you click the submit button, 
// it will post back to the PostTest action on the Home controller. Notice that Prop3 wasn't used
// so it won't be included in the postback
@model MyProject.Models.MyViewModel
<div>
    @using(Html.BeginForm("PostTest", "Home", FormMethod.Post))
    {
        @Html.TextBoxFor(m => m.Prop1);  
        @Html.HiddenFor(m => m.Prop2);

        <button type="submit">GO!</button>
    }
</div>

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // your index view is bound to MyViewModel so we'll hydrate that and send it to the view for rendering
        var viewModel = new MyViewModel();
        viewModel.Prop1 = "Property 1";
        viewModel.Prop2 = "Property 2";
        viewModel.Prop3 = "Property 3";

        return View(vm);
    }

    public ActionResult PostTest(MyViewModel vm) // mvc will attempt to deserialize your form data into this object
    {
        var testProp1 = vm.Prop1; // "Property 1"
        var testProp2 = vm.Prop2; // "Property 2"
        var testProp3 = vm.Prop3; // null
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为它实际上回答了这个问题.当前接受的答案只是说明如何在视图中使用模型数据,而不是如何在控制器中"返回"它. (2认同)