[英]Passing a lot of parameters to a controller?
我正在創建一個“高級輸入表單”,其中包含許多用於搜索數據的輸入。 我的問題是:從HTML向控制器傳遞大量數據的最佳方法是什么?
我問的原因是。 假設您有以下HTML表單:
@using (Html.BeginForm("Loading", "AdvancedSearch"))
{
<input type="text" id="keyword">
<input type="text" id="keyword1">
<input type="text" id="keyword2">
<input type="text" id="keyword3">
<input type="text" id="keyword4">
<input type="text" id="keyword5">
<input type="text" id="keyword6">
<input type="text" id="keyword7">
<input type="text" id="keyword8">
<input type="text" id="keyword9">
<input type="submit" value="Search" style="width: 150px;" />
}
然后將所有這些都傳遞給控制器是很討厭的(我有很多關鍵字):
public ActionResult Loading(string keyword1, string keyword2, string keyword3, string keyword4, string keyword5, string6
string keyword7, string keyword8, string keyword9){
//do things to the parameters!
return View();
}
那么,您將如何執行此操作或將您這樣做呢?
謝謝!
使用模型類。 只要輸入名稱與模型屬性匹配,MVC引擎將為您完成映射。
public class Keywords
{
public string keyword1 { get; set; }
public string keyword2 { get; set; }
///etc...
}
而且您的操作要簡單得多:
public ActionResult Loading(Keywords keywords){
//do things to the parameters!
var keyword1 = keywords.keyword1;
return View();
}
用那些keyword1,keyword2等創建一個類。
如
public class SearchDto
{
public string Keyword1 { get; set; }
public string Keyword2 { get; set; }
public string Keyword3 { get; set; }
public string Keyword4 { get; set; }
public string Keyword5 { get; set; }
public string Keyword6 { get; set; }
public string Keyword7 { get; set; }
public string Keyword8 { get; set; }
}
然后是ActionResult如
public ActionResult Loading(SearchDto dto)
{
return View();
}
您可以從視圖中發布數據。
這里有一個示例,它通過POST(ajax)發送JSON數據並從Controller(MVC)接收JSON響應 。
還有這里
function search() {
$.ajax({
type: "POST",
url: '@Url.Action("CreateEmail", "Email")',
data: JSON.stringify({
Keyword1 : $("#keyword1").val(),
Keyword2 : $("#keyword2").val(),
Keyword3 : $("#keyword3").val(),
Keyword4 : $("#keyword4").val(),
Keyword5 : $("#keyword5").val(),
Keyword6 : $("#keyword6").val(),
Keyword7 : $("#keyword7").val(),
Keyword8 : $("#keyword8").val(),
}),
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result){
alert('done');
}
)};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.