ASP.NET MVC go back to correct view - asp.net-mvc-3

I have Person controler with List Edit Create methods after edit of Person i go back to Person list
NOW I have other controler Family (Family - Person is one-to-many )
on Detail Family I have list of Persons with edit linked to Person/Edit/Id
When user clicks Save Person after editing I want to go back to Family Detail if he came from there or to Peron list if he Edited Person from Person list
Some help please
Thanks

You can use
HttpContext.Request.UrlReferrer
So to go back to the last view you would use something like:
Response.Redirect(HttpContext.Request.UrlReferrer.OriginalString);
Edit after comment:
Indeed you would get send back to the edit page in this case, what you could do if you don't want anyone to see querystrings is: (assuming you are using html.form to post the data).
On your Edit person page, inside of the form add something like:
#using (Html.BeginForm(new { RedirectUrl = HttpContext.Current.Request.UrlReferrer.OriginalString } )
and then on the controller pick it up as:
public Void Edit(int id, string RedirectUrl)
{
//save stuff
return Redirect(RedirectUrl);
}

You can pass the URL of the previous page in the query string for the edit page.

Related

reading related data after a selection of a foreign key - MVC3 and EF4

I am new to MVC and EF and I have a question.
I have built a site with models views controllers etc.
On an edit view for a Case (pretty big model so I won't post it here) I have a FK to a Customer model using CustomerID. When a user selects a customer id from a drop down list, I would like to display CustomerName, CustomerPhone etc after the selection of the ID. I think I might need to do a post back for this to work?
Also, do I need to Include the related entities as part of the initial data "get"? I have read some detail on that but I dont fully understand how that needs to work.
Please let me know if I should post more info. Thanks!
Here is my ActionResult for Edit
public ActionResult Edit(int id)
{
Cases cases = db.Cases.Find(id);
//related data needs to loaded to show related data fields
//include related data entities
var v = db.Cases.Include("Customers");
ViewBag.TechnicianID = new SelectList(db.Technicians, "TechnicianID", "LastName", cases.TechnicianID);
ViewBag.BranchID = new SelectList(db.Branches, "BranchID", "BranchName", cases.BranchID);
ViewBag.EngineModelID = new SelectList(db.EngineModels, "EngineModelID", "EngineModelName", cases.EngineModelID);
ViewBag.CaseCategoryID = new SelectList(db.CaseCategories, "CaseCategoryID", "CategoryName",cases.CaseCategoryID);
ViewBag.Qualified = new SelectList(new[] { "YES", "NO", "PARTIALLY" });
ViewBag.CaseStatus = new SelectList(new[] { "OPEN/IN PROCESS", "CLOSED" });
return View(cases);
}
The line
var v = db.Cases.Include("Customers")
is what I am trying to use to load related customer data and then show in my edit view like this:
#Html.EditorFor(model => model.Customer.CustomerName)
Well it depends on what you are trying to do. You could include a model which holds all the required data and send it with every call on that page (initial empty ofcourse)
Once you selected the customer, do post-back and send the customerId to your application and return the same page with the desired model.
You could do that via AJAX too.
Also, do I need to Include the related entities as part of the initial data "get"?
Not sure if I understand what you are trying to say. You mean that you think you would have to send all customer's data down to the page and select the related data on client side?

Send data from list to another list then edit in controller

My goal is to transfert data from a list to another. I was able to populates them, and now trying to do the rest. I want to add 2 buttons between the lists so I can send the data from both sides. I need help to code the button, and how to code the controller so I can collect the selected items in the lists (to remove and/or delete).
Here my model :
namespace OnlineTR.WebUI.Areas.Admin.Models
{
public class TestCategoryModel
{
public IEnumerable<TestCase> TestCasesAvailable { get; set; }
public IEnumerable<TestCase> TestCasesCurrent { get; set; }
}
}
View :
#model Models.TestCategoryModel
#Html.ListBoxFor(model => model.TestCasesAvailable, new SelectList(Model.TestCasesAvailable,"TestCaseId", "TestCaseName"))
#Html.ListBoxFor(model => model.TestCasesCurrent, new SelectList(Model.TestCasesCurrent, "TestCaseId", "TestCaseName"))
Alex,
I'd take a look at the jquery UI for the swapping scenarios if that is your use case. I've used a similar technique for a project that required ingredient categories to be added from one list to another. for this, I used jquery draggables and then saved the resultant 'list b' elements as part of a form post (via ajax). These examples may help for starters:
jQuery Draggable, Droppable, ASP.NET MVC
http://www.c-sharpcorner.com/UploadFile/krishnasarala/drag-and-drop-items-from-one-list-to-another-list-using-jque/
will follow up with more asap
Here is an example post...you may try this...it is similar to your problem...
http://www.codeproject.com/Articles/136730/ASP-NET-MVC-2-Basics-Working-with-ListBoxes
Although it is done in MVC 2...that dynamics/approach will still remain the same in MVC 3...

Storing model is session. Is there any better way for it?

I have a model class like following
public class ProductModel
{
string ProductName { get; set; }
int Quantity { get; set; }
}
In Controller I have an Action item
public ActionResult ShowProduct()
{
return View();
}
In my view user has two text boxes; where they enter product name and quantity. The first time they come in on this page these fields are empty. Once they enter values in these text boxes they hit a Next button which take them to a next page where they have to enter additional information about order.
On that page I have a back button and they can come back to this first page. Problem is I need to display the information that they entered in first page but on the second page I don’t have that ProductModel anymore. I can store that model in session but not sure if there is any better pattern of doing it in MVC
I would steer clear of Session and TempData. If you're using MVC, and your views are separated by full postbacks, (not Ajax) maybe you could use a view model pattern across different controller actions.
public class OrderController : Controller
{
public ActionResult ShowProduct()
{
return View(new ProductViewModel());
}
[HttpPost]
public ActionResult DoOrderStuff(ProductViewModel vm)
{
if (ModelState.IsValid)
{
// OrderViewModel would contain some product data
// to be used in the DoOrderStuff view
return View(new OrderViewModel(vm));
}
// error, go back to Page 1
return View("ShowProduct", vm);
}
}
This gives you room for validation while still following the wizard style views you described.
Caveat I just realized with this:
If you have a bunch of successive views, your user experience would probably suffer without a lot of hacking together of different view models. E.g. customer is on page 5 of the wizard, and wants to go back to page 2--my answer in its simplest form wouldn't accommodate that. However, with a good abstraction of the values in all your screens, it could be done.
This is pretty much what the Session dictionary was intended to be used for. You may look into using TempData but in essence it is just a lightweight version of Session. I don't see anything wroth with what you are doing.
I don't think you need to store this in the Session/TempData (watch out, how TempData works surprisingly changed quite a bit from MVC 2 to MVC 3). Your next button sounds like a POST, and then you do some sort of Redirect. If instead you made your form POST to the URL you wanted to display next, the ProductModel would be passed right along, and you could then pass it from the Action to the View, through either the Model or ViewData.

ASP.Net MVC View returned, but how can I show additional information?

I have a SQL database with has the following: Customer, Item, Clothing and Food.
Item holds a key to Clothing or Food.
Item also holds a key to Customer. Therefore a customer can have an item, which may be of food or clothing.
I am using ADO.Net Entity Framework and have this generated automatically.
I currently have the following set-up: A person may enter their ID on the webpage and this is sent via a form post where the controller picks it up and queries the database using LINQ to get the customer. The customer view (details) is then returned. I can now see all the customer details etc.
However, what I want is to be able to see the items the customer has, the different food items and clothing items, but I am unsure how to do this. I also want to be able to allow the user to edit one field of the clothes and food items tables. Any idea how I would implement this?
Here is an ActionResult in my CustomerController:
public ActionResult Details(int id)
{
var cust = (from c in dataModel.Customers
where (c.MembershipID == id)
select c).First();
return View(cust);
}
I can also write cust.Items which is the entity which I want to display in the view with the customer (their items). How would I display this in the view also?
Hopefully this makes it a little more clear on what I am trying to achieve and how.
Thanks.
Using Entity Framework, if you're tables are linked properly with the right foreign keys and all that then your Customer entity should have a property that is a collection of Items.
You could also create your own strongly typed ViewModel that has a field for Customer and implement your own properties for Clothing and Food and populate those with another query.
This question was asked last night but its similar. The guy in the question wanted information to populate a dropdown passed in. You want something similar, not for a dropdown, but to fill in textboxes to edit. How to properly populate drop downs from ViewData in controller on multiple views in ASP.NET MVC
To create a ViewModel start by creating a new class and name it CustomerAndItemsViewModel, for example.
public class CustomerAndItemsViewModel
{
public Customer Customer { get; set; }
public IQueryable<Items> Items { get; set; }
}
public ActionResult Details(int id)
{
var cust = (from c in dataModel.Customers
where (c.MembershipID == id)
select c).First();
var items = (from i in dataModel.Items
where (i.MembershipID == cust.MembershipID)
select i;
return View(new CustomerAndItemsViewModel { Customer = cust, Items = items });
}
And don't forget that you will no longer be passing a Customer to your view. So you need to change the line at the top to something like:
#model Your.Path.To.CustomerAndItemsViewModel
Typically, if you want to pass back information that is not contained in just one of your entities, you have to create a class that encompasses more than one object. So, if you want a page that displays your customer information, and all their items (which they can then edit), you would need to have a the controller action pass back a "CustomerAndItems" object (or something similarly named). This object would hold a reference to the Customer as well as a collection of their Items. (You build the CustomerAndItems object within your Action.)
Then, your view would be strongly typed to CustomerAndItems, and you can then display each piece of information as you normally would.

MVC pass query strings

I am new to Microsoft.MVC, so sorry if this is a silly question.
I have created a very simple forum, and I am now trying to create some tag functionality to it.
I have a controller where the index retrieves the last 10 forum threads. I would like to pass a query string, or something a-like with the Id to the supplied tag to the forum, so I thereby can get the forum threads, which e.g. have the tag 'ASP.NET'.
If it was a regular webforms project I would simply supply a query string with the tag id, to the index page, and then retrieve the forum threads with the tag, but isn't there a smarter way to do it in MVC.NET?
The reason why I ask, is it seems like a step backwards from REST-urls, to suddenly use 'regular' query strings?
First you define your action (like you probably already did), and add the parameters like you need them:
public ActionResult Forum(string tag, int page)
{
// do your thing
// ...
return View();
}
Then, in your Global.asax.cs, you can add a route that handles the parameters like you want them.
routes.MapRoute("Forum", "Forum/{tag}/{page}", new {controller = "Home", action = Forum"});
This will cause the Forum action to trigger on the HomeController when you go to the http://yourhost/Forum link. If you then click have a link like this http://yourhost/Forum/asp.net/1 Then "asp.net" will passed into the tag parameter, and 1 will be passed onto the page parameter.
You can use an ActionLink html helper. Assuming you have a forums controller and index page, to get a link to /forums/index/1?tag=asp.net you can do:
Html.ActionLink("ASP.NET", "index", new { id = 1, tag = "asp.net"})

Resources