I've been new to ASP.NET MVC. This is what I'm doing. I've 2 Controllers:Home and Customerservice.
Now I have a Customer list where when I click details gets redirected to the products he acquired.
So, I need to pass in the id so that the products of that customer can be displayed. So, my home consists of customer details. Now i need to pass that id to CustomerService controller ,Index action. This is what I've done in Home:
public ActionResult Customers()
{
var dc = new ServicesDataContext();
var query = (from m in dc.Customers
select m);
return View(query);
}
public ActionResult Details(int id)
{
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Customers.First(m => m.CustomerId == id);
ViewData.Model = serviceToUpdate;
// return View();
return Redirect("/CustomerService");
}
[HttpPost]
public ActionResult Details(FormCollection form)
{
var id = Int32.Parse(form["CustomerID"]);
var datacontext = new ServicesDataContext();
var service = datacontext.Customers.First(m => m.CustomerId == id);
return Redirect("Customers");
}
}
Now I'm not sure whether I need to pass an id as parameter for index in CustomerService. SO can you please guide me in finishing this?
If you are using any Redirect (such as RedirectToAction) you can use TempData to store any parameters. The semantics have slightly changed in MVC 3 but TempData is designed to pass data between actions in a POST-Redirect-GET scenario.
Passing it as a parameter is probably your best option. Try using something like return RedirectToAction(ActionName, ControllerName, RouteValues);.
Related
I'm wondering how I should do this: I get the ID of an item by using the asp-route-id="#item.ID" method.
<a asp-controller="Outfit" asp-action="OutfitRatingOpslaan"
asp-route-id="#item.ID" class="btn btn-primary">Beoordelen</a>
This ID needs to be remembered for the view:
public IActionResult OutfitRatingOpslaan(item.ID)
{
Object obj = Container.GetObject(item.ID)
}
So the ID of that object, needs to be combined with the value i get after pressing on a submit button in the OutfitRatingOpslaan(Item.ID) view.
I have added a picture on how the view looks like and where the user can enter a value.
This new value + the ID of the object need to be combined and stored inside database.
So the end result should look something like this:
public IActionResult OutfitRatingSave()
{
Rating rating = ratingContainer.AddRating(item.ID, Value);
}
Does anyone have any ideas ? ;p
There are two methods can achieve it.
First method, You can use:
return RedirectToAction("action", "controller", new { id = item.ID});
Then in target action, Just use :
public IActionResult OutfitRatingSave(int id)
{
Rating rating = ratingContainer.AddRating(id, Value);
}
Second method, You can use TempData["xx"] to pass data between actions, refer to below code:
public IActionResult OutfitRatingOpslaan(item.ID)
{
TempData["id"] = item.ID
Object obj = Container.GetObject(item.ID)
}
public IActionResult OutfitRatingSave()
{
int id = (int)TempData["id"];
Rating rating = ratingContainer.AddRating(id, Value);
}
I am trying to pass the parameter, which is 'priceValue'. How can I pass this value through using RedirectToAction? or do you have any idea for that?
I am trying to make shopping cart now. 'priceValue' is radioButton value. Could you give me some help? After passing the priceValue, and I want to use if statement what I have written in AddToCart. Is it possible to use it?
Please help me..
Thanks.
public class ShoppingCartController : Controller
{
rentalDB db = new rentalDB();
//
// GET: /ShoppingCart/
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our ViewModel
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
// Return the view
return View(viewModel);
}
// GET: /Store/AddToCart/5
[HttpPost]
public ActionResult AddToCart(int id, FormCollection col)
{
var addedProduct = db.Product
.Single(product => product.productId == id);
decimal priceValue = Convert.ToDecimal(col["price"]);
//how to pass priceValue to index
if (Convert.ToDecimal(col["price"]) == addedProduct.threeDayPrice)
{
ViewBag.price = new SelectList(db.Product, "productId", "threeDayPrice");
//How to put this value into cart.AddtoCart(addedProduct) with date and price
}
else if (Convert.ToDecimal(col["price"]) == addedProduct.aWeekPrice)
{
ViewBag.price = new SelectList(db.Product, "productId", "aWeekPrice");
//How to put this value into cart.AddtoCart(addedProduct) with date and price
}
// Retrieve the product from the database
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct);
// Go back to the main store page for more shopping
//I don't know how to pass the 'priceValue' by using RedirectToAction.
return RedirectToAction("Index", new {id = priceValue});
}
You have to add a parameter to your Index method in order to be able to get the value passed in to the Index method:
public ActionResult Index(int priceValue = 0).
Instead of 0, you can then use whatever default value you wish. Then calling
return RedirectToAction("Index", new {#priceValue = priceValue});
will allow you to get the value inside the method.
return RedirectToAction("Index", new {#id = priceValue.toString()});
will redirect it to an Action method called Index with a id parameter
Actually I'm very new to ASP.NET MVC and I need your help.
Here I have some Create Method that takes an argument from the URL to use it as id:
in 'vote' controller :
public ActionResult Create(int id)
{
Meeting meeting = db.Meetings.Find(id); // get the object
ViewBag.meetingID = meeting.meetingID; // get its id and assign it to a ViewBag
return View();
}
and I would like to do something like :
vote.meetingID = #ViewBag.meetingID
in the model so that is directly assgin this property without excplicitely typing it from the HTML view (I mean #Html.EditorFor(model=>meetingID) )
The question is not that clear, but try this.
You could pass the entire model to the view.
Controller:
public ActionResult Create(int id)
{
Meeting meeting = db.Meetings.Find(id); // get the object
ViewData["myMeeting"] = meeting;
return View();
}
To use in the view you can declare it as a variable at the top of the view:
Declare:
#
{
var meetingData = ViewData["myMeeting"] as Meeting;
}
Usage:
<div>
#meetingData.meetingID
</div>
If I have the usual Edit actions, one for GET to retrieve an object by it's ID and to display it in an edit form. The next for POST to take the values in the ViewModel and update the object in the database.
public virtual ActionResult Edit(int id)
[HttpPost]
public ActionResult Edit(VehicleVariantEditSaveViewModel viewModel)
If an error occurs during model binding in the POST action, I understand I can RedirectToAction back to the GET action and preserve the ModelState validation errors by copying it to TempData and retrieving it after the redirect in the GET action.
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
How do I then convert that ViewData, which includes the previous invalid ModelState, into a new model to send to the view so the user sees their invalid input with validation warnings? Oddly enough if I pass in a new instance of my ViewModel retrieved from the database (with the original valid data) to the View() this is ignored and the (invalid) data in the ViewData is displayed!
Thanks
I had a similar problem and decided to use the following pattern:
public ActionResult PersonalRecord(Guid id)
{
if (TempData["Model"] == null)
{
var personalRecord = _context.PersonalRecords.Single(p => p.UserId == id);
var model = personalRecord.ToPersonalRecordModel();
return View(model);
}
else
{
ViewData = (ViewDataDictionary) TempData["ViewData"];
return View(TempData["Model"]);
}
}
[HttpPost]
public ActionResult PersonalRecord(PersonalRecordModel model)
{
try
{
if (ModelState.IsValid)
{
var personalRecord = _context.PersonalRecords.Single(u => u.UserId == model.UserId);
personalRecord.Email = model.Email;
personalRecord.DOB = model.DOB;
personalRecord.PrimaryPhone = model.PrimaryPhone;
_context.Update(personalRecord);
_context.SaveChanges();
return RedirectToAction("PersonalRecord");
}
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors.First();
foreach (var propertyError in errors.ValidationErrors)
{
ModelState.AddModelError(propertyError.PropertyName, propertyError.ErrorMessage);
}
}
TempData["Model"] = model;
TempData["ViewData"] = ViewData;
return RedirectToAction("PersonalRecord", new { id = model.UserId });
}
Hope this helps.
I noticed that the Model is included in ViewData so you don't need to pass it in addition to the ViewData, what I don't understand is how you get at it to then return it to the view.
public ViewResult Edit(int id)
{
// Check if we have ViewData in the session from a previous attempt which failed validation
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
VehicleVariantEditViewModel viewModel = new VehicleVariantControllerViewModelBuilder()
.BuildForEdit(id);
return View(viewModel);
}
The above works but obviously it's making an unnecessary call to the database to build a new Model (which gets automagically overwritten with the invalid values from the Model in the passed ViewData)
Confusing.
I'm a beginner of MVC3 with ASP.Net (C#) but I don't get the next situation to delete a record.
I have a View that ask the user to confirm delete a item (record). As code I have this to initialize the view:
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return _db.SearchTerms.Where(x => x.id.Equals(id)).First();
}
But when confirmed, then I have the next code.
[HttpPost]
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
Building is not possible because the signature of this method is already exists (same parameters and method name).
So I don't get how to delete a record in this situation. The view is created with a default Scaffold template (delete).
I found an alternative solution to this problem while reading up on MVC. Check out: Improving the Details and Delete Methods
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id = 0)
{
// Delete stuff...
}
This will route the action Delete to the method DeleteConfirmed.
You can give your post function another additional parameter
[HttpPost]
public ActionResult KeywordsDelete(Guid id, FormCollection collection)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
But your GET Action should also return a View not a data object, I think.
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return View(_db.SearchTerms.Where(x => x.id.Equals(id)).First());
}