2013-02-25 27 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

相關問題