Data does not refresh in browser but does in database - asp.net-mvc

I have a working submit button, so when I make changes to my form and click submit the form updates to the changes...
HOWEVER. In the database it shows the new data. But when I RedirectToAction to the last page it doesn't show the updated data.
This is my code (Controller):
[HttpPost]
public ActionResult Save(M2Portal.Areas.Admin.Models.Users.Roles roleForm)
{
try
{
if (ModelState.IsValid)
{
var role = Srvctx.Roles.FirstOrDefault(w => w.RoleID == roleForm.RoleId);
role.RoleDescription = roleForm.RoleDescription;
Srvctx.SubmitChanges();
return RedirectToAction("RoleManagement");
}
return RedirectToAction("RoleManagement");
}
catch
{
return RedirectToAction("RoleManagement");
}
}
so when it hits:
return RedirectToAction("RoleManagement");
it just goes to the page but doesnt refresh the data. but when i look at my database its been changed there.
Am new to ASP.NET MVC and have no idea where to start looking...
Any ideas?
role mangagement:
public ActionResult RoleManagement(string userName)
{
return View("RoleManagement", new UserForm(userName));
}
Rolemangement cshtml:
#foreach (M2DAL.M2Service.Role r in Model.AllRoleIDs)
{
<tr>
<td>#r.RoleName</td> //This is not refreshing, on debug shows the number, but browser shows old number)
<td>#r.RoleID</td>
<td>#Html.ActionLink("Edit Roles", "EditRole", "Users", new { roleId = r.RoleID }, new { #class = "action" }) </td>
</tr>
}

You didn't post the code for RoleManagement action. I don't know where are you storing your model, but are you sure, that this action is reading the DB again ?
There should be something like (just an example)
[HttpGet]
public ActionResult RoleManagement()
{
var roles = Srvctx.Roles.Take(1000);
return roles;
}

Related

How to Pass Value from a login Page

Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});

Show a message from ViewBag set in a controller on an Exception and Stay in the same View

What I have
A single view 'AddEdit.cshtml' that is used to both Edit and also Delete a Student entity.
Edit ActionResult:
public ActionResult Edit(int Id)
{
// code to get the Student object create a VM and call the view passing the VM
ViewBag.Mode = "Edit";
return View("AddEdit", studentVm);
}
Delete button in the same view:
#Html.ActionLink("Delete Student", "Delete", new { id = Model.StudentId }, new { role = "button", #class = "btn btn-danger",id="deleteStudent" })
In case of an exception when deleting I want to inform the user by showing a message in a alert so I added this code:
public ActionResult Delete(int id)
{
var student = _publisherManager.GetStudentById(id);
try
{
_studentManager.DeleteStudent(student);
}
catch (Exception ex) {
// Logging code
ViewBag.DeleteStudentError = "This student is currently acitve and cannot be deleted.";
// Code to get the VM same as in the Edit method and call the view with it
return View("AddEdit", studentVm);
}
// All well go to the Index view
return RedirectToAction("Index");
}
Not able to do
Show the message from ViewBag
The Url after the click says
Student/Delete/14
Instead of
Student/Edit?Id=14
Any clues?
Thanks in advance.
Your url will be always Student/Delete/14. If you want to change this to Edit you must redirect your action.
That is,
public ActionResult Delete(int id)
{
var student = _publisherManager.GetStudentById(id);
try
{
_studentManager.DeleteStudent(student);
}
catch (Exception ex) {
// Logging code
// You can't use ViewBag because we will redirect to another action.
//ViewBag.DeleteStudentError = "This student is currently acitve and cannot be deleted.";
// You can use TempData to pass parameter across actions
TempData["DeleteStudentError"] = "This student is currently acitve and cannot be deleted.";
// Code to get the VM same as in the Edit method and call the view with it
return RedirectToAction("Action_Name_Of_Edit",student);
}
// All well go to the Index view
return RedirectToAction("Index");
}
And you can use this TempData["DeleteStudentError"] in your AddEdit.cshtml.
Your view should be,
<span class="alert"> #(TempData["DeleteStudentError"]??string.Empty) <span>

Foreach does not work while using json in asp.net mvc

,Hi all,
I am trying to use json.İf ı return to partial view ,i can not use foreach for my customer session.My Customer Session has customers.I can not list them.
Where i miss ?
CONTROLLER:
public ActionResult ShowResult(MyModel model)
{
Session["CustomerList"] = context.Customer.Where(s => s.CustomerSituation== true).ToList(); // Customers List To Session
var stringView = RenderRazorViewToString("_ShowResultPartial", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}
.
My _ShowResultPartial View:
#foreach (var item in (List<Q502351.Models.Customer>)Session["CustomerList"])
{
Ajax.ActionLink(item.CustomerName, "ShowResult", new { CustomerId = item.CustomerId}, new AjaxOptions { HttpMethod = "POST" });
}
From what you have posted, it's not clear why you want to store the customer list in session; data for the view should generally be stored on the view model. Even if you have a compelling reason to use session, it's a better practice to retrieve the session variables in the controller and store them in the view model. Then you should be able to loop through the list on the model from the view. In this situation it doesn't look like session is necessary at all (unless you intend to reuse the stored data later and for some reason cannot pass it along via models).
Also, unless there is a good reason to return json, your ShowResult controller method should just return a PartialView.
Something like this should work...
Controller:
public ActionResult ShowResult(MyModel model)
{
model.Customers = context.Customer.Where(s => s.CustomerSituation == true).ToList();
return PartialView("_ShowResultPartial"), model);
}
Partial view:
#model MyModel
#foreach (var item in Model.Customers)
{
Ajax.ActionLink(item.CustomerName, "ShowResult", new { CustomerId = item.CustomerId}, new AjaxOptions { HttpMethod = "POST" });
}

Unwanted caching in MVC application

I have an issue with caching and have tried every solution I can find!
I have a simple create screen where one row is inserted in a table (although I also get the same issue when editing existing rows).
When the row is created, the user is returned to the previous screen, which still shows the old data. (same issue with edit)
Refreshing the page makes no difference. Difference browsers have the same problem. The data is successfully added in the database. Only by restating the application does it refresh the data on screen.
Things I have tried:
1:
DataContext.Refresh(RefreshMode.OverwriteCurrentValues)
2:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
3:
ModelState.Clear()
None of which made any difference. I've not had this problem before with edits or creates, so I must be missing something. Any help much appreciated!
The following is the relevant parts of the controller:
ISISDataContext db = new ISISDataContext(StudentISIS.Properties.Settings.Default.ISISConn.ToString());
public ActionResult Index()
{
var student = (ISIS2Models.Student)Session["CurrentUser"];
return View(student);
}
public ActionResult STGCreate(int id)
{
var enrolment = db.Enrolments.Single(e => e.EnrolmentID == id);
return View(enrolment);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult STGCreate([Bind(Exclude = "Id")] StudentGrade STGToCreate, FormCollection collection)
{
var STG = new StudentGrade();
STG.Grade = collection["StudentTG"];
STG.EnrolmentID = int.Parse(collection["Enrolment"]);
STG.DateChanged = DateTime.Now;
db.StudentGrades.InsertOnSubmit(STG);
db.SubmitChanges();
return RedirectToAction("Index");
}
Edit:
Here is the code from the index view which loops through enrolments to show the grade:
<%foreach (var en in Model.Enrolments) {%>
//Some table stuff
<td>
<%try
{ %>
<%= Html.ActionLink(en.StudentGrades.Grade,"STGEdit",new {controller = "Progress", id = en.StudentGrades.StudentGradeID})%>
<%}
catch (NullReferenceException) {%><%= Html.ActionLink("Set","STGCreate",new {controller = "Progress", id = en.EnrolmentID})%><% } %>
</td>
//Some more table stuff
<%}%
Where do the rows come from? is it your ISIS2Models.Student class? I can only assume it is because you have so little code in your Index method.
If it is, and you are storing that in the session, then you are not updating that value, so when you retrieve it from within Index it will still have the same old values.
What you need to do is get the updated model from the database each time you make a call to Index. Some method like this:
public ActionResult Index()
{
var currentUser = (ISIS2Models.Student)Session["CurrentUser"];
var student = GetStudentById(currentUser.ID);//this will get the up-to-date student record from the DB
return View(student);
}

ASP.NET MVC: Server Validation & Keeping URL paramters when returning the view

I currently have the following code for the POST to edit a customer note.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
else
{
var _customer = _customerRepository.GetCustomer(new Customer() { CustomerID = Convert.ToInt32(note.CustomerID) });
var _notePriorities = _customerRepository.GetNotePriorities(new Paging(), new NotePriority() { NotePriorityActive = true });
IEnumerable<SelectListItem> _selectNotePriorities = from c in _notePriorities
select new SelectListItem
{
Text = c.NotePriorityName,
Value = c.NotePriorityID.ToString()
};
var viewState = new GenericViewState
{
Customer = _customer,
SelectNotePriorities = _selectNotePriorities
};
return View(viewState);
}
}
If Validation fails, I want it to render the EditNote view again but preserve the url parameters (NoteID and CustomerID) for something like this: "http://localhost:63137/Customers/EditNote/?NoteID=7&CustomerID=28"
Any ideas on how to accomplish this?
Thanks!
This action is hit by using a post. Wouldn't you want the params to come through as part of the form rather than in the url?
If you do want it, I suppose you could do a RedirectToAction to the edit GET action which contains the noteId and customerId. This would effectively make your action look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
//It's failed, so do a redirect to action. The EditNote action here would point to the original edit note url.
return RedirectToAction("EditNote", "Customers", new { id = note.CustomerID.ToString() });
}
The benefit of this is that you've removed the need to duplicate your code that gets the customer, notes and wotnot. The downside (although I can't see where it does it here) is that you're not returning validation failures.

Resources