传递复杂类型作为动作方法的参数。 MVC

时间:2017-04-27 13:36:42

标签: c# asp.net-mvc razor

将数据传递给action方法时遇到问题。我按照以下方式在视图中创建了操作链接:

@model ComplexModel

...

<a href=@Url.Action( "ComplexAction", "ComplexController", new { complex= @Model, str = "string" } )
class="ui-btn">!!!Change all</a>

用于获取所有传递参数的动作方法:

public ActionResult ComplexAction( ComplexModeloAufgabeViewModel complex, string str )
{
    return View();
}

正确传递字符串,但复杂模型总是为空。这里发生了什么?

2 个答案:

答案 0 :(得分:0)

您需要使用以下格式发布复杂类型:

using (Html.BeginForm("ComplexAction", "ComplexController")
{
    // form fields go here

    <input type="submit" value="save" />
}

这会发布您的ViewModel @model ComplexViewModel定义的复杂类型。

您的操作将按如下方式读取ViewModel:

public ActionResult ComplexAction(ComplexViewModel model)
{
    // do stuff with the form values here
}

答案 1 :(得分:0)

您必须使用表单才能使模型绑定器正常工作

@model SomeComplexViewModel

@using Html.BeginForm("Action", "Controller")
{
   // fields for every one of the complex type properties
   Html.TextBoxFor(m=>m.FirstProperty)

   <input type="submit" value="submit" />
}

然后在动作方法中,您将收到模型