how to pass value of viewmodel from controller to another controller - asp.net

i try to create some application using MVC 4. in my application, i can create new promo. how can i pass value from Create to Index when i using ViewModel for parameter in Index.
this my Index
public ActionResult Index(ViewModel.Rate.RateViewModel search)
{
var RoomType = _RoomTypeService.GetRoomTypeName(_HotelID);
var currency = _CurrencyService.GetAllCurrency();
XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel vm = new ViewModel.Rate.RateViewModel();
if (search.Request == null)
{
vm.RoomTypeList = ViewModel.DropDown.Builder.RoomTypeBuilder.Build(RoomType, null);
vm.CurrencyList = ViewModel.DropDown.Builder.CurrencyBuilder.Build(currency, null);
}
else
{
vm.RoomTypeList = ViewModel.DropDown.Builder.RoomTypeBuilder.Build(RoomType, search.Request.RoomTypeID);
vm.CurrencyList = ViewModel.DropDown.Builder.CurrencyBuilder.Build(currency, search.Request.Currency);
}
vm.Request = search.Request;
if (search.Request == null)
{
vm.Request = new RateRequest();
vm.Request.CheckInFrom = null;
vm.Request.CheckInTo = null;
vm.Request.RoomTypeID = null;
}
if (search.Request != null)
{
Session["RoomTypeID"] = search.Request.RoomTypeID;
Session["Breakfast"] = search.Request.Breakfast;
Session["Currency"] = search.Request.Currency;
}
vm.listRoomRate = GetDataIndex(vm.Request);
_UserSession.SearchRoomRate = vm;
return RedirectToAction("SearchResult");
}
my New
[HttpPost]
public ActionResult New(ViewModel.Rate.RateViewModel vm)
{
if (vm.NewRoomRate.Currency == null)
vm.NewRoomRate.Currency = "IDR";
var NewData = _RoomRateService.NewRoomRate(vm.NewRoomRate.RoomTypeName, vm.NewRoomRate.Breakfast,
Convert.ToDateTime(vm.NewRoomRate.CheckInFrom), Convert.ToDateTime(vm.NewRoomRate.CheckInTo), vm.NewRoomRate.sun, vm.NewRoomRate.mon, vm.NewRoomRate.tue,
vm.NewRoomRate.wed, vm.NewRoomRate.thu, vm.NewRoomRate.fri, vm.NewRoomRate.sat, vm.NewRoomRate.Currency, vm.NewRoomRate.SingleRate,
vm.NewRoomRate.DoubleRate, vm.NewRoomRate.TripleRate, Convert.ToDecimal(vm.NewRoomRate.Commision), Convert.ToInt32(vm.NewRoomRate.Allotment), vm.NewRoomRate.CloseSelling,
vm.NewRoomRate.FreeSell);
if (NewData == null)
{
ModelState.AddModelError("failed", "RoomRate is already created, please use edit instead");
return New();
}
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
test.Request = new RateRequest();
test.Request.RoomTypeID = Convert.ToInt32(vm.NewRoomRate.RoomTypeName);
return RedirectToAction("Index", new {search = test.Request });
}
i try like this, but i get error like this
Server Error in '/' Application.
The model item passed into the dictionary is of type '<>f__AnonymousType0`1[XNet.WebUI.Hotel.ViewModel.RateRequest]', but this dictionary requires a model item of type 'XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel'.
can some one tell me, how i can do this?
thanks

according to the error you are getting:
Server Error in '/' Application.
The model item passed into the dictionary is of type '<>f__AnonymousType0`1[XNet.WebUI.Hotel.ViewModel.RateRequest]', but this dictionary requires a model item of type 'XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel'.
you are specifying that Index will recieve a parameter of type: ViewModel.Rate.RateViewModel named search.
public ActionResult Index(ViewModel.Rate.RateViewModel search)
but you are passing an object of type ViewModel.Rate.RateViewMode in your "NEW" action result.
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
test.Request = new RateRequest();
test.Request.RoomTypeID = Convert.ToInt32(vm.NewRoomRate.RoomTypeName);
return RedirectToAction("Index", new {search = test.Request });
to resolve the error you can edit your controller like this:
[HttpPost]
public ActionResult New(ViewModel.Rate.RateViewModel vm)
{
if (vm.NewRoomRate.Currency == null)
vm.NewRoomRate.Currency = "IDR";
var NewData = _RoomRateService.NewRoomRate(vm.NewRoomRate.RoomTypeName, vm.NewRoomRate.Breakfast,
Convert.ToDateTime(vm.NewRoomRate.CheckInFrom), Convert.ToDateTime(vm.NewRoomRate.CheckInTo), vm.NewRoomRate.sun, vm.NewRoomRate.mon, vm.NewRoomRate.tue,
vm.NewRoomRate.wed, vm.NewRoomRate.thu, vm.NewRoomRate.fri, vm.NewRoomRate.sat, vm.NewRoomRate.Currency, vm.NewRoomRate.SingleRate,
vm.NewRoomRate.DoubleRate, vm.NewRoomRate.TripleRate, Convert.ToDecimal(vm.NewRoomRate.Commision), Convert.ToInt32(vm.NewRoomRate.Allotment), vm.NewRoomRate.CloseSelling,
vm.NewRoomRate.FreeSell);
if (NewData == null)
{
ModelState.AddModelError("failed", "RoomRate is already created, please use edit instead");
return New();
}
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
return RedirectToAction("Index", new {search = test });
}
hope that helps.

Related

I have Pull the value of ImagelocationID from dropdown through database using foreign key and While creating I got this error

This is my Controller
public async Task <IActionResult> SliderImage(ImageUploadViewModel imageUpload)
{
string stringFilename = UploadFile(imageUpload);
var branch = _context.BranchPages.Single(b => b.BranchId == imageUpload.ImageContentPageId);
var Sliderimage = new ImageContentModel
{
ImageOrderNo = imageUpload.ImageOrderNo,
ImageName = imageUpload.ImageName,
ImageLocation = imageUpload.ImageLocation,
RelatedLinks = imageUpload.RelatedLinks,
Image = stringFilename,
ImageContentPageId = Convert.ToInt32(branch),
};
_context.ImageContents.Add(Sliderimage);
await _context.SaveChangesAsync();
return View();
}
Error i have got
InvalidCastException: Unable to cast object of type 'H20_CafeAndPub.Models.BranchPageModel' to type 'System.IConvertible'.
System.Convert.ToInt32(object value)
H20_CafeAndPub.Controllers.HomePageController.SliderImage(ImageUploadViewModel imageUpload) in HomePageController.cs + var Sliderimage = new ImageContentModel
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
You need to change the few code like this
Change 1 :
var branch = _context.BranchPages.Where(b => b.BranchId == imageUpload.ImageContentPageId).FirstOrDefault();
Change 2 :
ImageContentPageId = Convert.ToInt32(branch.Id)

View not update after POST although View Model updated

I am writing ASP.NET Custom Component, I want to update my view with following code below:
#if (Model.TableDatasource != null){
//Write some thing to html page example: tables or span
}
At the first, Model.TableDatasource is null, user choose information and Controller Review View(Model) like this:
var model = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
};
if (request == null)
{
return View(model);
}
else
{
var currentPlant = JsonConvert.DeserializeObject<PlantList>(request);
var FullModel = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
CurrentPlant = JsonConvert.DeserializeObject<PlantList>(request),
DriverList = JsonConvert.DeserializeObject<List<Drivers>>(CommonHelper.GetDriver(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
CustomerList = JsonConvert.DeserializeObject<List<Customer>>(CommonHelper.GetCustomer().Content.ReadAsStringAsync().Result),
RecipeList = JsonConvert.DeserializeObject<List<Recipe>>(CommonHelper.GetRecipe(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
SitesList = JsonConvert.DeserializeObject<List<Site>>(CommonHelper.GetSite().Content.ReadAsStringAsync().Result),
// TruckList = JsonConvert.DeserializeObject<List<Truck>>(CommonHelper.GetTruck().Content.ReadAsStringAsync().Result)
};
return View(FullModel);
}
At the Debug time, I notice that break-point stop at return View(FullMode) and Break-point at ViewFile(cshtml) has value. but nothing printed at view.
Hope some help.

Cannot post update to database. not all code paths return a value

[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
return View(user);
}
}
I keep on getting an error while saving data to the database.
UpdateDetail worked while retrieving message, but i keep getting error when saving.
Your issue is if your ModelState.IsValid == false, then you are not returning anything. I put a comment in code below where it is.
Depending on what your logic needs to do, would determine what needs to be returned if IsValid == false
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
// this is your issue, this needs to be outisde the if statement, or you have to do an else and return null (or whatever you need to based off your logic)
return View(user);
}
}
Keep return statement outside of If statement. this would fix your error.If model is valid model updated with user details from database will be pushed to View. other wise same user model will be pushed to the view.
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
}
return View(user);
}

Values returned from my Repository model class is being cached

I have the following Post Edit action method:-
[HttpPost]
[ValidateAntiForgeryToken]
[CheckUserPermissions(Action = "Edit", Model = "StorageDevice")]
public ActionResult Edit(SDJoin sdj, FormCollection formValues)
{
//code goes here
if (ModelState.IsValid)
{
repository.Save();
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (TMSStorageDevice)entry.GetDatabaseValues().ToObject();
var clientValues = (TMSStorageDevice)entry.Entity;
var databaseTechnology2 = repository.FindTechnology2(sdj.StorageDevice.TMSStorageDeviceID);
if (sdj.NetworkInfo.IPAddress != databaseTechnology2.TechnologyIPs.SingleOrDefault(a=>a.IsPrimary == true).IPAddress )
ModelState.AddModelError("NetworkInfo.IPAddress", "Value Has Changed "
);
if (sdj.NetworkInfo.MACAddress != databaseTechnology2.TechnologyIPs.SingleOrDefault(a => a.IsPrimary == true).MACAddress)
ModelState.AddModelError("NetworkInfo.MACAddress", "Value Has Changed "
);
if (databaseValues.RackID != clientValues.RackID)
ModelState.AddModelError("StorageDevice.RackID", "Value Has Changed "
);
But currently the values returned from the
var databaseTechnology2 = repository.FindTechnology2(sdj.StorageDevice.TMSStorageDeviceID);
will return a cached value inside the server , instead of retrieving the current database value. The repository method is :-
public Technology FindTechnology2(int id)
{
return tms.Technologies.Include(a=>a.TechnologyIPs).SingleOrDefault(a => a.TechnologyID == id);
}
Can anyone advice ?
I'm posting this as a follow up to my comment in order to show code properly.
You can set MergeOptions.OverwriteChanges as follows:
var objectContext = ((IObjectContextAdapter)entities).ObjectContext; //assuming 'entities' is your context here
var set = objectContext.CreateObjectSet<TechnologyRoles>();
set.MergeOption = MergeOption.OverwriteChanges;
var query = set.SingleOrDefault(a => a.TechnologyID == id);
Hope this helps,

Pass a value from controller to view

I have a problem in passing a value from controller to view
In controller, In the edit method
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
Now in edit's view , I used this
#Html.Encode(ViewData["CustomerID"])
This is my Index method
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
But the customerID on the page turns to be null.. Can u let me know if this procedure is correct?
You don't need to requery the id. Just use the id directly:
if (ModelState.IsValid)
{
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = id});
}
Since you are redirecting the ViewData["CustomerID"] will be lost.
However the id in your Index method should be valid.
If your Index View requires the ViewData["CustomerID"] set it in your Index action:
public ActionResult Index(int id)
{
ViewData["CustomerID"] = id;
//....
I'm a bit confused as to which view does not have access to ViewData["CustomerId"]. If it's the Index view, you should set ViewData["CustomerId"] = id there.

Resources