2015-02-07 29 views
0
[HttpGet] 
    public ActionResult Index() 
    { 

     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(FormCollection fc) 
    { 
     String sc = fc["SearchString"]; 
     return RedirectToAction("SearchFromObject", new { id = sc }); 
    } 

    public ActionResult SearchFromObject(string searchString) 
    { 
     var Items = from m in db.Objects 
        select m; 
     if (!String.IsNullOrEmpty(searchString)) 
     { 
      Items = Items.Where(s => s.Name.Contains(searchString)); 
     } 
     return View(Items); 
    } 

此代碼爲String sc返回空值。爲什麼??在我看來,有一個文本box.i希望該值傳遞給SearchFromObject方法作爲參數點擊按鈕和檢索到搜索keyword..Here是我的看法FormCollection在mvc中返回空值

@{ 
ViewBag.Title = "Search"; 
} 

<h2>Search</h2> 
<p> 

@using (Html.BeginForm()) 
{<p> 
    Title: @Html.TextBox("SearchString") <br /> 
    <input type ="submit" value="Search" /> 
</p> 
} 
+0

您能不能告訴你呈現的查看HTML?現在看起來好了。 – 2015-02-07 18:52:47

回答

0

你的方法

public ActionResult SearchFromObject(string searchString) 

有一個名爲searchString參數,但在Index() POST方法,您嘗試使用new { id = sc }傳遞名爲id的參數。它的值不是sc的值是null,它的值在searchString的第二個GET方法中是null

更改POST方法簽名

[HttpPost] public ActionResult Index(string SearchString) 
{ 
    return RedirectToAction("SearchFromObject", new { searchString = SearchString}); 
} 
+0

它的工作原理!!!!!!感謝名單! – 2015-02-08 13:41:12

0

指定您的post方法的相關數據時,控制器名稱和形式操作是這樣的:

@using (Html.BeginForm("Index", "Default1", FormMethod.Post)) 
{  
    <p> 
    Title: @Html.TextBox("SearchString") <br /> 
    <input type ="submit" value="Search" /> 
</p> 
} 
+0

'@using(Html.BeginForm())'會添加默認值,這正是你所做的(假設控制器名稱爲'Default1Controller'),所以這是不必要的,除非你指定了不同的控制器或動作。 – 2015-02-07 22:46:45