well i m having 2 hyperlinks :
Fr
|
Ang
in my controller i used this to change the current langage
[HttpPost]
public ActionResult Fr()
{
ContentModelView CMV = new ContentModelView();
//Langue:
int CurrentLanguageid = db.Langues.FirstOrDefault(x => x.active_langue == "true").id_langue;
Langues LangueA = db.Langues.Find(CurrentLanguageid);
LangueA.active_langue = "false";
db.SaveChanges();
int NextLanguage = db.Langues.FirstOrDefault(x => x.txt_langue == "fr").id_langue;
Langues LangueB = db.Langues.Find(CurrentLanguageid);
LangueB.active_langue = "true";
db.SaveChanges();
return (RedirectToAction("../Home/Index"));
}
[HttpPost]
public ActionResult Ang()
{
ContentModelView CMV = new ContentModelView();
//Langue:
int CurrentLanguageid = db.Langues.FirstOrDefault(x => x.active_langue == "true").id_langue;
Langues LangueA = db.Langues.Find(CurrentLanguageid);
LangueA.active_langue = "false";
db.SaveChanges();
int NextLanguage = db.Langues.FirstOrDefault(x => x.txt_langue == "en").id_langue;
Langues LangueB = db.Langues.Find(CurrentLanguageid);
LangueB.active_langue = "true";
db.SaveChanges();
return (RedirectToAction("../Home/Index"));
}
but i don t know if i m obliged to use a parametre in my methode because it s an httpost and it send me to /Home/Fr not the index even after forcing the method no change in database i m struggling with this problem
Clicking on the link element(anchor tag) will issue a GET request.Your action methods are marked with HttpPost and it will not be hit from your GET action request generated by clicking in the link. You have 2 options
Change remove the [HttpPost] decorator from the action method
Hijack the click event on the link and make an http post ajax call.
Also i notice that you have duplicate code in the two methods except the language code you use in your where clause. Why not use a single method with a parameter where you can pass the language code ?
public ActionResult UpdateLanguage(string id)
{
//This is your existing code. I did not verify the correctness of this!
var CMV = new ContentModelView();
//Langue:
int CurrentLanguageid = db.Langues.FirstOrDefault(x => x.active_langue == "true")
.id_langue;
Langues LangueA = db.Langues.Find(CurrentLanguageid);
LangueA.active_langue = "false";
db.SaveChanges();
int NextLanguage = db.Langues.FirstOrDefault(x => x.txt_langue == id).id_langue;
Langues LangueB = db.Langues.Find(CurrentLanguageid);
LangueB.active_langue = "true";
db.SaveChanges();
if(Request.IsAjaxRequest())
return Json(new { status="success"},JsonRequestBehavior.AllowGet);
return RedirectToAction("Index","Home");
}
Now, to make the ajax call, you may simply add a css class to the links
<a class="languageLink" href="#Url.Action("UpdateLanguage", "Home",new {id="fr"})">Fr</a>
<a class="languageLink" href="#Url.Action("UpdateLanguage", "Home",new {id="en"})">En</a>
Now the js code to hijack the link click event and make an ajax call
$(function(){
$("a.languageLink").click(function(){
$.post($(this).attr("href"),function(data){
window.location.href="#Url.Action("Index","Home")";
});
});
});
Related
I'm creating an application that books Guests in hotelrooms. In the HttpGet I pass a ReservationViewModel from my Controller to the View. This VM contains all the reservationdetails and 2 empty Guest objects (or however many). For each Guest object I show a form where the user needs to enter information about the Guest. However when I try to submit it only returns the info of one Guest. I've tried looking for a way to pass an array or multiple guests, but that doesn't seem to be possible, only sending one Guest object with parameters seems to work..
Here is the code for my GET:
[HttpGet]
public ActionResult Edit2(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reservation reservation = resRepo.GetReservationByID(id);
ReservationVM reservationVM = new ReservationVM(0);
for (int i = 0; i < reservation.amount_people; i++)
{
reservationVM.guests.Add(new Guest());
}
foreach(Guest guest in reservationVM.guests)
{
guest.name = " ";
guest.zipcode = " ";
guest.housenumber = 0;
guest.suffix = "";
guest.email = " ";
guestRepo.AddGuest(guest);
}
guestRepo.Save();
reservationVM.date = (DateTime)reservation.date;
reservationVM.amount_people = (int)reservation.amount_people;
reservationVM.ID = reservation.ID;
reservationVM.room_ID = (int)reservation.room_ID;
if (reservation == null)
{
return HttpNotFound();
}
return View(reservationVM);
}
And my POST:
[HttpPost]
public ActionResult Edit2([Bind(Include = "room_ID,date,amount_people,ID")]Reservation reservation, [Bind(Include = "ID,name,zipcode,housenumber,suffix,email")]Guest guest)
{
if (ModelState.IsValid)
{
resRepo.UpdateReservation(reservation);
resRepo.Save();
guestRepo.UpdateGuest(guest);
guestRepo.Save();
Reservation r = new Reservation { ID = reservation.ID };
db.Reservations.Add(r);
db.Reservations.Attach(r);
Guest g = new Guest { ID = guest.ID };
db.Guests.Add(g);
db.Guests.Attach(g);
r.Guests.Add(g);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reservation);
}
and my form for completion:
Form
Now I was wondering how to pass all the forminfo to my Controller and use that information to save the Reservation and each Guest, so I can write that to my db.
Thanks!
EDIT: I tried the solution given, but I can't seem to get the Guest information in my database. Problem seems to be that when it reaches the foreach loop to get the guests out of reservationVM it's empty. Tried writing to Debug output whenever it entered the loop but it never does. Here's my code
[HttpPost]
public ActionResult Edit2(ReservationVM reservationVM)
{
if (ModelState.IsValid)
{
//Get reservation
Reservation reservation = resRepo.GetReservationByID(reservationVM.ID);
//Update values in model
reservation.date = reservationVM.date;
reservation.amount_people = reservationVM.amount_people;
reservation.ID = reservationVM.ID;
reservation.room_ID = reservationVM.room_ID;
//Update to DB and save changes
resRepo.UpdateReservation(reservation);
resRepo.Save();
foreach (Guest guest in reservationVM.guests)
{
Guest temp = guestRepo.GetGuestByID(guest.ID);
temp.name = guest.name;
temp.zipcode = guest.zipcode;
temp.housenumber = guest.housenumber;
temp.suffix = guest.suffix;
temp.email = guest.email;
temp.ID = guest.ID;
guestRepo.UpdateGuest(temp);
reservation.Guests.Add(temp);
}
guestRepo.Save();
//Reservation r = new Reservation { ID = reservation.ID };
//db.Reservations.Add(r);
//db.Reservations.Attach(r);
//Guest g = new Guest { ID = guest.ID };
//db.Guests.Add(g);
//db.Guests.Attach(g);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reservationVM);
}
You are passing ReservationVM from view to the post method. So write your post method as follows:
[HttpPost]
public ActionResult Edit2(ReservationVM reservationVM)
{
if (ModelState.IsValid)
{
// Here access the necessary values you need from `reservationVM` and do your necessary stuffs
return RedirectToAction("Index");
}
return View(reservation);
}
To get your guest information in you post action, you need to make the guest fields as follow:
#for(var i = 0; i < Model.guests.count; i++)
{
Your editor will be like below
#Html.EditorFor(model => model.guests[i].ID)
#Html.EditorFor(model => model.guests[i].name)
}
try making the fields in razor view like the above code .. it’ll work.
Am trying to pass data from jquery to asp.net mvc controller to get a response but fails to work
This is what i have tried
In jquery
$('#Emp_Payroll_No').change(function () {
var empdata = $(this).val();
$.post('/tblHandOvers/GetEmployee', { payrollno: empdata}).then(function (res) {
console.log("response is", res); //res is always empty
})
})
In my c# code
public JsonResult GetEmployee(HttpContext context)
{
context.Response.ContentType = "text/plain";
string passedtext = context.Request.Form["payrollno"].ToString();
var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == passedtext);
return Json(PersonsQuery);
}
so am trying to pass payrollno
When using a manual value eg: EMP2001 in the controller it works like
public JsonResult GetEmployee(HttpContext context)
{
var PersonsQuery = db.vwEmployee_HandoverContact
.Where(x => x.Emp_Payroll_No == "EMP2001 "); //passed manually
return Json(PersonsQuery);
}
How do i go about this?
In your C#, I would update to this:
public JsonResult GetEmployee(string payrollno)
{
var PersonsQuery = db.vwEmployee_HandoverContact.Where(x => x.Emp_Payroll_No == payrollno);
return Json(PersonsQuery);
}
I got a problem with visual studio 2013. I have two actions in my controller: ActionResult VerifyRequest and ActionResult b.
public ActionResult VerifyRequest()
{
Utility.SessionKeys sessionKeys = new Utility.SessionKeys();
Session.Add(sessionKeys.InvoiceNumber, result.OrderId);
payment.TrackingCode = result.VerifyResultData.SystemTraceNo;
payment.state = 3;
payment.Confirmed = true;
payment.Transactionsuccess = true;
db.Entry(payment).State = EntityState.Modified;
db.SaveChanges();
melliBank.ResCode = result.VerifyResultData.ResCode;
melliBank.OrderId = result.VerifyResultData.OrderId;
melliBank.RetrivalRefNo = result.VerifyResultData.RetrivalRefNo;
melliBank.SystemTraceNo = result.VerifyResultData.SystemTraceNo;
melliBank.InvoiceDate = payment.IssueDate;
melliBank.Succeed = result.VerifyResultData.Succeed;
melliBank.Amount = result.VerifyResultData.Amount;
melliBank.Description = result.VerifyResultData.Description;
melliDB.InsertMelliBankLog(melliBank);
ReservType reserv = db.ReservTypes.Find(payment.ReserveType);
//string url = string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"), reserv.ConfirmUrl);
//return Redirect(url);
return RedirectToAction(reserv.ConfirmUrl.Split('/')[1], reserv.ConfirmUrl.Split('/')[0]);
}
public ActionResult b()
{
return View();
}
Here is the deal:
When i use RedirectToAction("b") from action "VerifyRequest" to action b after return action "VerifyRequest" execute again. And also when action b get completes, action "VerifyRequest" execute again too.
I don't know how to solve this problem and what is bug. Please help me.
Sometimes "VerifyRequest" execute 4 times after redirect
For RedirectToAction we have to pass actionmethod name
try this:-
return RedirectToAction("b);
I have a problem. I'm trying to redirect my application using a controller method, like this:
[HttpPost]
public ActionResult GetSelected(string Selected, string NewRoleID)
{
var StringSelected = Selected.Split(',');
for (var i = 0; i < StringSelected.Count(); i++)
{
if (StringSelected[i] == "true")
{
R_ROLEMENU newMenu = new R_ROLEMENU();
newMenu.RoleID = int.Parse(NewRoleID);
newMenu.MenuID = i + 1;
var existing = (from item in db.RoleMenus
where (item.RoleID == newMenu.RoleID && item.MenuID == newMenu.MenuID)
select item).ToArray();
if (existing.Count() == 0)
{
db.RoleMenus.Add(newMenu);
db.SaveChanges();
}
}
else
{
R_ROLEMENU oldMenu = new R_ROLEMENU();
oldMenu.RoleID = int.Parse(NewRoleID);
oldMenu.MenuID = i + 1;
var existing = (from item in db.RoleMenus
where (item.RoleID == oldMenu.RoleID && item.MenuID == oldMenu.MenuID)
select item).ToArray();
if (existing.Count() != 0)
{
db.RoleMenus.Remove(existing[0]);
db.SaveChanges();
}
}
}
return RedirectToAction("Logout", "Home");
}
And I'm calling the method with jquery, like this:
$.post("/m_menu/getselected?selected=" + selectedmenus + "&newroleid=" + roleid, function () {
//todo
});
The problem is, the application keeps redirected to index page instead of the Logout action in Home Controller. What am I doing wrong? The rest of the code within the controller is running fine, it's just the redirection that's not working. Please help, thank you
As it is an ajax call RedirectToAction will simply return the action called view as response of post you have to redirect via jquery in $.post call back function:
In Action instead of:
return RedirectToAction("Logout", "Home");
do:
return Content(Url.Action("Logout", "Home"));
and in call back of $.post do this:
$.post("/m_menu/getselected?selected=" + selectedmenus + "&newroleid=" + roleid, function (response) {
window.location = response;
});
or call call javascript at the end of action:
var script = "window.loaction ='"+Url.Action("Logout","Home")+"' ;";
return JavaScript(script);
I am getting a 500 error when I post my AJAX form via clicking the submit button. The controller that handles the AJAX post is getting the data fine but when I return the Partial View, via this line, I am getting the 500:
return PartialView("_SiteSurveyNewClubTeam", model);
The reason I am returning the partial back instead of a HTTP status code is because if I don't, one of my dynamic dropdowns comes back unpopulated. Maybe I am pinting myself into a corner, here.
The data types supplied in the offending DropDownListFor() I believe are correct and in the right order: (string, IList<SelectListItem>)
Error
The ViewData item that has the key 'DistrictSelected' is of type 'System.String'
but must be of type 'IEnumerable<SelectListItem>'.
View Model Declarations
public IList<SelectListItem> DistrictSelect { get; set; }
public string DistrictSelected { get; set; }
Source of the Error is this line in my View
<span class="formColumn2">#Html.DropDownListFor(model => model.DistrictSelected, Model.DistrictSelect)</span>
Not sure why I am getting this. Any ideas?
Thanks
Here is the code that processes the AJAX form post
[HttpPost]
public ActionResult ProcessFormANewClubTeam(FormANewClubTeamViewModel model)
{
var httpStatus = HttpStatusCode.BadRequest;
var cosponsors = new List<NewClubSponsor>();
var errorMessages = new StringBuilder();
var tasks = new NewClubBuilderTasks();
var clubKeyNumber = tasks.GetClubKeyNumber();
var masterCustomerId = tasks.GetMasterCustomerId();
bool exceptionRaised = false;
if (ModelState.IsValid)
{
if (model.NewClub_Id > 0)
{
//Load the entity to be partially-updated
NewClub newClub = db.NewClubs.Single(nc => nc.Id == model.NewClub_Id);
//Set the values for the fields to be updated
newClub.District = model.DistrictSelected;
newClub.Division = model.DivisionSelected;
newClub.Region = Utility.Personify.GetRegionFromDistrict(newClub.District);
newClub.ClubCounselorMasterCustomerId = model.ClubCounselorMasterCustomerId;
newClub.ClubCounselorContact = model.ClubCounselorContact;
newClub.ClubCounselorEmail = model.ClubCounselorEmail;
newClub.ClubCounselorPhone = model.ClubCounselorPhone;
newClub.DateUpdated = DateTime.Now;
try
{
//Execute the UPDATE
var dbResult = db.SaveChanges() > 0;
httpStatus = HttpStatusCode.OK;
}
catch (SqlException ex)
{
//Catch exceptions here
}
// return new HttpStatusCodeResult((int) httpStatus);
return PartialView("_SiteSurveyNewClubTeam", model);
} else {
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new {x.Key, x.Value.Errors})
.ToArray();
return new HttpStatusCodeResult((int) httpStatus);
}
}
You have to repopulate your select list items in your DistrictSelect list in the post action. Your viewmodel that was posted has DistrictSelect as null, this is why you are getting that exception when you render your partial.