Redirecting View by Id - asp.net-mvc

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.

Related

Null route value passes in ActionLink

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)

Use Action link and query string

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()

What do I have to do to redirect on same page's controller after clicking on Action link

View
#Html.ActionLink("Edit","Name",new { id = item.Id })
controller
[HttpPost]
public ActionResult Action_Result_Name(Model_Name Obj_Model, string Add, int id)
{}
When I click on actionlink I want to redirect in Same page contoller.
But when I put ("int id") in actionResult form it won't go into controller for the first time
Your ActionLink will create is a HTTP GET and your controller's action is decorated with HTTPPOST attribute.
What you should be using is a PRG pattern: POST-REDIRECT-GET.
For example: If you have a page for list of products and an edit (GET) action to edit a single product. Your View should have a form that posts the edited product to a HTTP POST action and then within that action you redirect to a GET:
Product Controller Actions:
[HttpGet]
public ActionResult Get(int id)
{
//Get product by id
var productRepository = new ProductRepository();
var product = productRepository.GetProductById(id);
return View(product);
}
[HttpGet]
public ActionResult Edit(int id)
{
//Get product by id
var productRepository = new ProductRepository();
var product = productRepository.GetProductById(id);
return View(product);
}
[HttpPost]
public RedirectToActionResult Edit(Product product)
{
//validation checks should happen first
//if model state is valid then save product
var productRepository = new ProductRepository();
var productId = productRepository.Save(product);
return RedirectToAction("GetProduct", new {id = productId});
}
EditProduct View:
#model Product
<form action="/product/edit" method="POST">
#*
Place HTML to show your HTML edit controls
to allow users to edit Product values
*#
</form>
There are a lot of things that are basic here. You may want to make sure you use a DI framework like Ninject, StructureMap etc so that all your repositories. But it at least gives you a general idea.
Hope this helps.

ASP.NET MVC, email address as parameter breaking routes

I have the following actionresult:
public ActionResult Confirmation(string emailAddress)
When I try to access it:
http://localhost:8080/Signup/Confirmation?emailAddress=test%40test.com
I get this:
The view 'test#test.com' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Signup/test#test.com.cshtml
~/Views/Signup/test#test.com.vbhtml
What gives why isn't it looking for the correct view? If I go to "/SignUp/" it correctly shows me the index, along with the other ActionResults working correctly. Why does an address break it?
You shouldn't be passing that info in the URL anyway.
If this is kind of a "Confirmation" page from a signup, you could pass another identifier, e.g the UserId that has just been created, then fetch it from the repo.
E.g:
[HttpPost]
public ActionResult Signup(SignupViewModel model)
{
//.. code to save.. etc
return RedirectToAction("Confirmation", new { id = newUser.UserId });
}
[HttpGet]
public ActionResult Confirmation(int id)
{
var user = repo.FindById(id);
// map to model, etc...
return View(model);
}
So your URL would be (without a specialized route)
http://localhost:8080/Signup/Confirmation?id=123213
Putting user's email addresses in the URL is asking for them to be spammed.
Have you tried registering the route in the global.asax.cs?
Something like:
routes.Add("confirmation",
new Route("Signup/Confirmation/{email}",
new RouteValueDictionary(new { controller = "Signup", action = "Confirmation", email = UrlParameter.Optional }),
new MvcRouteHandler())
);

ASP.NET MVC Create on a Master-Detail Relationship

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.

Resources