从Controller中获取模型中的值

时间:2014-03-17 12:31:00

标签: 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";
    }

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

感谢并抱歉“新生”:)

2 个答案:

答案 0 :(得分:7)

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

@Html.TextBoxFor(m => m.MyProperty); 

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

@Html.HiddenFor(m => m.MyProperty);

所以当你发回这个表单时会发生什么,它将作为表单数据(键值对)发送回通过提交表单调用的控制器操作。 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
    }
}

答案 1 :(得分:0)

该方法不会为您的模型设置任何值。您需要设置模型,然后将其传递给视图。

例如,您的控制器将是这样的:

public ActionResult Index()
{
    var modelObj = new MyModel();
    modelObj.name="MyName";
    modelObj.email="someone@mymail.com";
    modelObj.company="MyCompany";
    modelObj.message="Some text here";

    return View(modelObj);
}

完成此操作后,该模型将可在您的视图中使用。

对应的Razor视图Index.cshtml可以是这样的:

@model MyModel

<p>Name: @Model.name</p>
<p>Email: @Model.email</p>
<p>Company: @Model.company</p>
<p>Message: @Model.message</p>

HTH