2013-02-25 78 views
0

我有一个视图,它通过调用一个动作来呈现,我将视图模型传递给它,例如Vm1然后填充一些下拉列表。如何将c#对象发布到视图中的操作?

在这个视图上,我有一个带有一些文本框和一个“过滤器”按钮的“过滤器”部分,我想调用另一个操作传递文本框的值,然后部分渲染第二个视图在一个div内的页面。

所以我这样做,我的动作看起来像下面这被称为阿贾克斯点击“过滤器”按钮时:

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

因为我有大约10文本框,我想创建一个新的C#对象和传球是反对这一行动看起来像这样是简单的:

ActionResult ActionName(MyActionFilters myFilters) 

如何实现这一目标?

回答

0

您需要的表单输入名称设为您的视图模型的属性,然后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)和帮手将正确命名一切。

<input type="text" name="MyActionFilters.YOUR_PROPERTY_NAME" /> 

顺便说一句,您的操作方法应该HttpPost属性来注释:

0

输入标签的name属性,应该由对象名称( “MyActionFilters”)

例如前缀。

[HttpPost] 的ActionResult ActionName(MyActionFilters myFilters的)

+0

HttpPost可以返回一个PartialView吗? ajax可以发布帖子吗? – 2013-02-26 09:53:40

+0

当然!您可以使用JQuery进行发布:$ .ajax({type:“POST”,url:url,data:data,success:function(data){$('#someelement')。html(data);},dataType : 数据类型});并返回一个HTML视图,并将添加到您的页面上。要做post请求检查:http://api.jquery.com/jQuery.post/ – adpmatos 2013-02-27 10:39:04

1

你可以有一个模型如下面

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

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

可以传递在获取操作方法中的空模型

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!

+0

谢谢。我不喜欢改变页面,这些可能是PartialViews并被加载到页面上的div? – 2013-02-26 08:51:16

+0

所以我应该创建一个包含搜索过滤器和搜索结果的单独部分视图或每个部分视图? – 2013-02-26 09:39:00

+0

搜索过滤器将始终存在,搜索结果将作为局部视图加载。看到我的更新回答。 – 2013-02-26 18:00:58

相关问题