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>();
           ..
        }
4

2 回答 2

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);
}
于 2012-07-30T05:47:49.343 回答
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 );
        }
于 2012-07-30T11:44:54.563 回答