Is it possible to separate the ID in a URL (Home/Index/ 10 ) from a form submit that uses HttpPost and pass them to a controller?
Further explaination
A code example could be:
[HttpPost]
public ActionResult Index(int id, CustomerInfo info)
{
/*
* Code
*/
Return View();
}
CustomerInfo is an object which in this case would contain an int called "ID" and other customer related info.
If I submit a form and want to pass a CustomerInfo ID and a url parameter id both the url id and CustomerInfo.id will be the CustomerInfo id which I passed from the form. If I don't pass a CustomerInfo ID they both will be the url parameter id.
Simply looking at the url id in the controller isn't an option as I need to check if an ID is given in CustomerInfo or not.
I understand that I can just give the CustomerInfo ID another name (eg. CustomerInfoID) but would like to know if I can keep the url parameter id and the CustomerInfo ID the same names.
In the image above you'll see my issue. I did NOT provide an ID for CustomerInfo.ID. It simply passed it to there from the url parameter id when I submit my form. I want the ID of CustomerInfo to be empty when I don't provide one.
If you want to send both things you need to abstract it out by building a view-model thus:
public class ViewModel()
{
public CustomerInfo info {get; set;}
public int id {get; set;}
}
Send this to your view instead of CustomerInfo
[HttpGet]
public ActionResult Index()
{
ViewModel vm = new ViewModel()
{
info = info,
id = 0
}
return View(vm);
//changed from below:
//return View(info);
}
Anything in your view that references CustomerInfo
does this via the view-model now, for example:
@Html.TextBoxFor(t => t.InfoText)
is now
@Html.TextBoxFor(t => t.info.InfoText)
...
Accept it in your post argument:
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
/*
* Code
*/
int id = viewModel.id;
CustomerInfo info = viewModel.info;
Return View();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.