以下代码是我输入的示例 在我向控制器提交传递空值后,在控制器中我使用了类名,然后正确传递值,但是当我使用参数时,它将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 :(得分: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);
}
答案 1 :(得分: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 );
}