2012-07-30 100 views
1

在下面的代碼是樣品我輸入 我提交傳遞空值到控制器之後,在控制器我已經使用了類名字然後值傳遞正確,但是當我使用的參數將它傳遞NULL值到控制器。請給我一個解決方案..提交後,將空值傳遞給控制器​​中的參數?

控制器:

[HttpGet] 
     public ActionResult Index() 
     { 
      return View(); 
     } 


     [HttpPost] 
     public ActionResult Index(string firstname) 
     { 
      LogonViewModel lv = new LogonViewModel(); 
      var ob = s.Newcustomer(firstname) 

      return View(ob); 
     } 

查看:

@model IList<clientval.Models.LogonViewModel> 

@{ 
    ViewBag.Title = "Index"; 
} 

@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < 1; i++) 
    { 
    @Html.LabelFor(m => m[i].UserName) 
    @Html.TextBoxFor(m => m[i].UserName) 
    @Html.ValidationMessageFor(per => per[i].UserName) 

    <input type="submit" value="submit" /> 
    } 
} 

型號:

public class LogonViewModel 
    { 
     [Required(ErrorMessage = "User Name is Required")] 
     public string UserName { get; set; } 
    } 



    public List<ShoppingClass> Newcustomer(string firstname1) 
     { 

      List<ShoppingClass> list = new List<ShoppingClass>(); 
      .. 
     } 

回答

0

它的工作。我已經改變了我的控制器下面寫

控制器:

[HttpGet] 
     public ActionResult Index() 
     { 
      return View(); 
     } 


     [HttpPost] 
     public ActionResult Index(IList<LogonViewModel> obj) 
     { 

      LogonViewModel lv = new LogonViewModel(); 
      var ob = lv.Newcustomer(obj[0].FirstName) 

      return View(ob); 
     } 
0

此:

[HttpGet] 
public ActionResult Index() { 
    return View(); 
} 

不給你這個在您的視圖:

@model IList<clientval.Models.LogonViewModel> 

這:

for (int i = 0; i < 1; i++) { 
    @Html.LabelFor(m => m[i].UserName) 
    @Html.TextBoxFor(m => m[i].UserName) 
    @Html.ValidationMessageFor(per => per[i].UserName) 

    <input type="submit" value="submit" /> 
} 

不會與這方面的工作:

[HttpPost] 
public ActionResult Index(string firstname) { 
     LogonViewModel lv = new LogonViewModel(); 
     var ob = s.Newcustomer(firstname) 
     return View(ob); 
} 

你不發送一個模型到您的視圖,並且您在視圖中使用了一個列表,但期望在您的控制器中使用單個字符串值。你的例子或你的代碼有些非常奇怪/錯誤。

爲什麼你有一個IList的爲你的模型?如果您只需要使用單個輸入字段渲染表單。你應該有這樣的代碼:

[HttpGet] 
public ActionResult Index() { 
    return View(new LogonViewModel()); 
} 

和視圖:

@model clientval.Models.LogonViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(m => m.UserName) 
    @Html.TextBoxFor(m => m.UserName) 
    @Html.ValidationMessageFor(m => m.UserName) 

    <input type="submit" value="submit" /> 
} 

和控制器上的第二個動作:

[HttpPost] 
public ActionResult Index(LogonViewModel model) { 
    if (ModelState.IsValid) { 
     // TODO: Whatever logic is needed here! 
    } 
    return View(model); 
} 
+0

舉個例子,我輸入了這個,但實際上我在控制器中傳遞了很多參數... – Sham 2012-07-30 05:50:37

+0

如果這個例子不是很接近實際的代碼,而且你的例子很奇怪。 – 2012-07-30 05:59:45