Reputation: 63
My POST controller isn't able to capture the ViewModel parameter I set and I'm very confused as I have a different set of POST controller and it can capture the ViewModel parameter.
My code looks like this,
View Page
@model MyProject.Web.ViewModels.MyViewModel
@{
ViewBag.Title = "Home";
ViewBag.Description = "My Project";
ViewBag.SubDescription = "My Project Tool";
Layout = null;
}
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Filter)
<input type="submit" class="btn btn-primary btn-inline-right input-tab" value="Search" />
}
Controller
using MyProject.Web.ViewModels;
[HttpGet]
[Route("Home/Index")]
public async Task<ActionResult> Index()
{
...await API integration code here...
return View(MyViewModel);
}
[HttpPost]
[Route("Home/Index/{viewmodel}")]
public ActionResult Index(MyViewModel viewmodel) <-- all properties of viewmodel are NULL
{
return View();
}
View Model
using MyProject.Web.Models;
using System.Collections.Generic;
namespace MyProject.Web.ViewModels
{
public class MyViewModel
{
public User UserInfo;
public List<Client> Clients;
public string Filter;
}
}
I feel this is a very small mistake, maybe due to overlooking too much. Hopefully someone could take a look and help.
Upvotes: 2
Views: 826
Reputation: 18973
Change from public string Filter
to property public string Filter {get;set;}
and change route to [Route("Home/Index")]
instead of [Route("Home/Index/{viewmodel}")]
.
I tested and it worked.
public class MyViewModel
{
public User UserInfo { get; set; }
public List<Client> Clients { get; set; }
public string Filter { get; set; }
}
[HttpPost]
[Route("Home/Index")]
public ActionResult Index(MyViewModel viewmodel)
{
return View();
}
Upvotes: 0
Reputation: 2135
The problem is with the route you have defined on the top of your Post
action [Route("Home/Index/{viewmodel}")]
You don't need that {viewmodel}
in that URL as you are not posting anything in the query string, you are posting a complex object inside the body of your HTTP Post.
Remove that route
and it should work.
also, ASP.NET mvc maps the inputs to the Model properties based upon the name
attributes on them like <input name="abc">
will map this input to a property named abc
on a ViewModel or just a parameter. In your case @Html.TextBoxFor(m => m.Filter)
does that automatically.
Hope this helps.
Upvotes: 2
Reputation: 1350
use this I hope useful:
@using (Html.BeginForm("Index", "HomeController", FormMethod.Post))
Upvotes: 0