2012-04-23 62 views
1

我目前正在编写一个web应用程序,它需要将一些配置设置从设置页面传递到带有搜索框的页面页面。在MVC中的视图之间传递数据

目前我正在从设置页面传递配置数据到主页用:

public ActionResult Settings(Configuration configuration) 
{ 
    return RedirectToAction("ConfigSet", "Home", configuration); 
} 

和家庭控制器:

public ActionResult ConfigSet(Configuration configuration) 
{    
    return View("Index"); 
} 

我产生了局部视图:

public PartialViewResult Search(string q) 
    { 
     List<Stuff> results = this.Search(q); 
     return PartialView("SearchResults", results); 
    } 

随着渲染像这样的局部视图:

@using (Ajax.BeginForm("Search", "Home", new AjaxOptions { 
HttpMethod = "GET", 
InsertionMode = InsertionMode.Replace, 
UpdateTargetId = "searchResults", 
})) 
{ 
    <input type="text" name="searchString" /> 
    <input type="submit" value="Search" /> 
} 

我的问题是如何将配置设置传递给部分视图?我一直在想这个问题几天,我对此感到困惑。

回答

2

您可以创建一个视图模型将保存您的配置设置这样

public class MyViewModel 
{ 
    public Configuration configuration {get;set;} 
    public List<Stuff> results {get;set;} 
} 

在你的行动回报MyViewModel

public PartialViewResult Search(Configuration config)  
{ 
    var model = new MyViewModel(); 
    //set its properties  
    model.results = this.Search(q);  
    model.configuration = configurationObject;  
    return PartialView("SearchResults", model);  
} 

&如果要再次传递配置到控制器然后

@using (Ajax.BeginForm("Search", "Home", new { config = Model.configuration } new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults", })) 
{  
    <input type="text" name="searchString" />  
    <input type="submit" value="Search" /> 
} 
+0

谢谢。但是,我不确定如何将设置页面上设置的配置传递给搜索viewresult方法。我可以通过configset方法将数据传递给母版页,但无法使用您的想法将配置传递给搜索方法。 – 2012-04-23 13:09:35

+0

在您的ajax.beginform中,您可以从model.configuration呈现所有配置内容;在ajax请求提交哪个将要调用搜索动作,为此,你将不得不将签名更改为'公共PartialViewResult搜索(配置配置)' – 2012-04-23 14:02:24

+0

更新了答案,看看 – 2012-04-23 14:10:25

0

你的意思是你想得到你的配置文件服务器上搜索操作方法中的离子设置?要做到这一点,你必须将它们传送到客户端并返回,这似乎不合逻辑,可能不安全(取决于配置中的内容),或者需要在搜索操作本身内再次检索它们。

+0

配置设置由用户在视图中设置。然后他们将返回到主页(我有两个视图单独的控制器)。如果从HomeController调用this.search方法,如何将配置设置发送到搜索类? – 2012-04-23 14:18:36

+0

您是否将用户设置保存到数据库?如果没有,你真的只是在讨论会话设置,在这种情况下,你需要使用服务器的Session对象本身,或者将它们存储在一个cookie中,或者存储在每个视图的ViewModel上,有一个叫做UserSettings的公共属性,它是一个字符串,您可以序列化并反序列化每个请求。如果你做后者,有一个BaseViewModel可以帮你完成工作。 – 2012-04-23 18:14:40

相关问题