I am new to Asp.net MVC. I want to create the hyper Links of some object of Model in this way
<ul>#foreach(Department department in #Model )
{
<li>#Html.ActionLink(department.Name, "Index", "Employee", new {departmentid= department.Id },null)</li>
} </ul>
Now as it shows, when I click on Link in browser, it should move to Index action of employee controller with department.Id route value.But when I click the link, it passes a null route value, but in URL , it shows the correct value. Why is that like this? Any help?
this is the Index Action in Employee controller
public ActionResult Index(int id)
{
List<Employee> employees = new List<Employee>();
employees.AddRange(db.Employees.ToList().Where(x => x.DepartmentId == id));
return View(employees);
}
Your implmenting your action call wrong. the names in the anonymous object (new {departmentid= department.Id }) and the parameter names must match. Change departmentid to id (because your action expects a parameter called id Index(int id)):
#Html.ActionLink(department.Name, "Index", "Employee", new {id= department.Id },null)
Related
I want to use an actionlink to call a controller. My URL is
localhost:16252/Concert/Index/9.
I want to call create controller and send id (9) to the controller. How to access the id (9) from address bar by actionlink?
ActionLink has one overload that allows you to specify routevalues
MSDN Link here
#Html.ActionLink("LinkText", "Action", "Controller", new {Id= 9}, null)
For Passing from View you have to use overload which takes parameter of RouteValueDictionary:
#Html.ActionLink("Link Text","MyAction", "My", new {id= 9},null)
and in your controller:
public class MyController
{
public ActionResult MyAction(int id)
{
// do something
return View();
}
}
Using this overload of Html.ActionLink()
I have 2 tables tbl_client and tbl_branch linked with the client_id. I have created a ClientController and a BranchController.
Now I need to control the branch under client view. I have and ActionLink
#Html.ActionLink("Branch Management", "Index", "Branch", new {id = item.client_id},null)
This will redirect to Index view in branch controller, where the list of branches according to client id is filtered and return the view.
Now I have a create link in this view and I need to redirect it to the Create Page which will Create the Branch Under the Client currently active.
just put the client_id in a viewbag from your Branch-> Index actionresult.
Public ActionResult Index(string id){
ViewBag.ClientId=id;
}
now goto its view; Index.cshtml and say,
#Html.ActionLink("New Client", "Create", "Client", new {id = ViewBag.ClientId});
Just Make a Link into View as:
#Html.ActionLink("Branch Create", "Create", "Branch", new {id = item.client_id})
and on Server side (i.e. In Controller) use action as:
//GET
public ActionResult Create(long Client_ID)
{
var NewBranch=new BranchViewModel{Client_ID=Client_ID};
return View(NewBranch);
}
//POST
[HttpPost]
public ActionResult Create(BranchViewModel Branch)
{
//Code to Create New Entry
}
Maybe this can help you.
I am trying to construct an #Html.ActionLink to return to a previous page but to return to the previous page I need to pass in an id parameter.
ShowController/Details list a film defined by a int id, within this list is a link to go and look at the director details:
#Html.ActionLink( "(Director Bio)", "Index", "Director", new { searchString = item.Director.Name }, null)
When the user wants to go back to the film the StoreController/Details ActionResult is waiting for an int it.
I have tried to pass in the id to a viewBag:
public ActionResult Details(int id)
{
var item = from s in db.Shows.Where(si => si.ShowId == id) select s;
ViewBag.id = id;
return View(item);
}
And this shows fine in the Details view I cannot pick it up in the DirectorController/Index view to use in the actionLink, what do I do?
I've got a very basic ASP.Net MVC project where I'd like to use a parameter name of id on one of my controller actions. From everything I've read that shouldn't be a problem but for some reason using a parameter name of id fails to get the value extracted from the query string but if I change it to any other different name it will work.
I only have a single route in my global.asx
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
My controller method is:
public ActionResult Confirm(string id)
{
....
}
A URL of http://mysite/customer/confirm/abcd works. A URL of http://mysite/customer/confirm?id=abcd fails.
If I change the controller method to:
public ActionResult Confirm(string customerID)
{
....
}
then a URL of http://mysite/customer/confirm?customerID=abcd works.
Is there something special about using "id" as a parameter in an ASP.Net MVC query string?
Update: Changed id from 1234 to abcd, my id's are actually strings.
If you do not apply an id parameter (either querystring or POST), the system just ignores it, and you can remove the "id" parameter in your controller:
public ActionResult Confirm()
In your case, you would just stick with the id parameter. Why make an ugly customerID parameter, when id is "mapped" automatically?
This is an easy and simple example of the use of id parameter.
public ActionResult Confirm(int? id)
{
if (id.HasValue && id.Value > 0) // check the id is actually a valid int
_customerServer.GetById(id.Value);
// do something with the customer
return View();
}
This works too, for me. We're doing it in our application right now with a standard route:
public ActionResult Confirm(string id)
{
if (!string.IsNullOrEmpty(id)) // check the id is actually a valid string
_customerServer.GetByStringId(id);
// do something with the customer
return View();
}
If you need to have id in query string, then don't create route with 'id' parameter.
In case you have route "{controller}/{action}" then you can use public ActionResult Confirm(string id) as your controller method.
Routes don't care about query strings.
I am displaying an list of Items for a given Order. When a user clicks Add Item I redirect to the Item / Create page. This page collects that necessary input but also needs to know the order id that the item belongs to. What is the appropriate way to pass the OrderID to the Item / Create so that it survives the form post when the newly created item is saved.
I've played with TempData and writing the id out on the detail page via Html.Encode(). It gets me part of the way there in that the id shows up on the item form but the value is lost when the form submits and posts. I suppose because its not part of the formcollection. I am guessing my workaround is not the best way and would like to know if anyone can point out the proper way to do this in asp.net mvc.
I do this by creating a new route for the Item controller that includes the OrderId. It doesn't make sense to have an Item without an Order, so the OrderId is required using the constraints parameter.
routes.MapRoute(
"OrderItems",
"Item/{action}/{orderId}/{id}",
new { controller = "Item" },
new { orderId = #"d+" }
);
So the url would look like http://<sitename>/Item/Create/8, where 8 is the OrderId for which to create an item. Something similar could be done for Delete action routes with http://<sitename>/Item/Delete/8/5, where 8 is the OrderId and 5 is the ItemId.
Your Action methods would look like this:
public ActionResult Create(int orderId)
public ActionResult Delete(int orderId, int id)
You could also set it up so that the urls looked like http://<sitename>/Order/8/Item/Create and http://<sitename>/Order/8/Item/Delete/5 if that seems to more clearly show what's going on.
Then the route would look like this:
routes.MapRoute(
"OrderItems",
"Order/{orderId}/Item/{action}/{id}",
new { controller = "Item" },
new { orderId = #"d+" }
);
I've used this sequence (sorry if there are mistakes, I took this from a working example and modified it for your question):
1) In the Order.Details view (assume Model is of type Order):
...
<%= Html.ActionLink("Create New Item", "Create", "OrderItem", new { orderId = Model.ID }, null)%>
...
2) In the OrderItem.Create action:
public ActionResult Create(int orderId)
{
ViewData["orderId"] = orderId;
return View();
}
3) In the OrderItem.Create view:
...
<% using (Html.BeginForm(new { orderId = ViewData["orderId"] }))
...
4) In the OrderItem.Create POST action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(int orderId)
{
// omitted code to create item, associated with orderId
return RedirectToAction("Details", "Order", new { orderId = orderId });
}
If anyone can think of how to improve on this, or of a better way altogether, please chime in, I'm sort of new to this myself so I'd like to improve.
To round-trip a field that's not part of the normal data entry, I generally use a hidden field in the view, like this:
<%= Html.Hidden("OrderID", Model.OrderID) %>
It looks like a form field, acts like a form field, but the user cannot see it. Make sure you push the correct OrderID into your model from the controller.