如何将c#对象发布到视图中的动作?

时间:2013-02-25 17:39:22

标签: c# asp.net-mvc jquery

我有一个通过调用动作呈现的视图,并且我将视图模型传递给它,例如然后Vm1填充一些下拉列表。

在这个视图中,我有一个“过滤器”部分,其中包含一些文本框和一个“过滤器”按钮,我想调用另一个动作传递文本框的值,然后在页面上部分呈现第二个视图在一个div。

所以我已经完成了这个,当点击“过滤器”按钮时,我的动作如下所示,由ajax调用:

ActionResult ActionName (string inputText1, string inputText2, string inputText3, ...)

因为我有大约10个文本框,所以我想创建一个新的c#对象并将该对象传递给此动作,看起来更简单:

ActionResult ActionName(MyActionFilters myFilters)

如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

你可以有一个模型如下

public class MyActionFilters
{
  public string Property1{get;set;}
  public string Property2{get;set;} 
  public string[] Property3{get;set;} 

  // add any number of properties....
}

您可以在Get Action方法中传递空模型

ActionResult ActionName()
{
  MyActionFilters myEmptyActionFilers= new MyActionFilters();
  View(myEmptyActionFilers)
}

形式

Html.TextBoxFor(model => model.Property1)
Html.TextBoxFor(model => model.Property2)

然后在post方法中,您可以访问表单中填充的模型 我删除了以前的代码。新代码在编辑标签之后:)

编辑: 对不起,我不在身边。使用AJAX可以轻松实现这种功能:)

如下所示。

[HttpPost]
PartialViewResult ActionName(MyActionFilters myActionFilers)// this is magic
{
  /*you can access the properties here like myActionFilers.Property1 and pass the 
    same object after any manipulation. Or if you decided have a model which contains 
    a variable to hold the search results as well. That is good.*/

   return PartialView(myActionFilers);
}

到目前为止this是一个很好的例子。

不要忘记在视图中添加jquery.unobtrusive-ajax.js脚本引用。如果不是Ajax不会影响。在给定的例子中,他已经在_Layout中完成了它,你可以看到。

PS:明智地选择将要传递给视图的模型的属性并享受Ajax!

答案 1 :(得分:0)

您需要将表单输入名称设置为ViewModel的属性,然后MVC将做一些魔术来制作例如:

public class FormViewModel {
    public string input1 {get;set;}
    public string input2 {get;set;}
    // and so on
}

然后是你的行动:

public ActionResult FormPost(FormViewModel model) {
    // you'll have access to model.input1, model.input2, etc
}

最后,例如,您要在HTML表单上创建:

<input type="text" name="input1" />
<input type="text" name="input2" />

或者您可以使用Html.TextBoxFor(model => model.Input1),帮助程序会正确命名所有内容。

答案 2 :(得分:0)

输入标记的name属性应以对象名称为前缀(“MyActionFilters”)

例如:

<input type="text" name="MyActionFilters.YOUR_PROPERTY_NAME" />
不过,你的动作方法应该用HttpPost属性注释。

[HttpPost] ActionResult ActionName(MyActionFilters myFilters)