Reputation: 333
I am creating a form with a drop down for a property named "Event". Unfortunately this is a reserved word so it won't work as usual:
@Html.DropDownListFor(x => x.Event, new SelectList(ViewData["Events"] as IEnumerable<JFS.Data.Model.Event>, "Id", "Name"))
In the controller I can't take this value separately as it is a reserved word, so if I do this:
public ActionResult Create(int event)
{
etc etc
}
It throws an error.
What I would ideally like to do is change the name of the dropdown list, something like this:
@Html.DropDownListFor(x => x.Event as eventId, new SelectList(ViewData["Events"] as IEnumerable<JFS.Data.Model.Event>, "Id", "Name"))
But that doesn't work. Anyone know of the correct way to change the name? :-)
Upvotes: 0
Views: 2001
Reputation: 1038850
You cannot change the name generated by HTML helpers and this is by design. What you could do instead is to change the name of your action parameter and prefix it with @
which allows to use reserved words in C# as variable names:
public ActionResult Create(int @event)
{
etc etc
}
But in general it is not recommended to use reserved words as variable names unless absolutely necessary. And in your case it is not absolutely necessary because there's a much better solution which of course consists in using a view model:
public class CreateEventViewModel
{
public int Event { get; set; }
}
and then having your controller action take this view model as argument:
public ActionResult Create(CreateEventViewModel model)
{
etc etc
}
Upvotes: 2