I am using one controller which is inserting values in the database. I want to display alert message from controller when the values insertesd in the database successfully.
Is it possible. If yes then how?
You can add the result to ViewData. For example:
if (SaveToDbOK)
{
ViewData["Success"] = "Data was saved successfully.";
// Do other things or return view
}
In your view you can place anywhere:
MVC2:
<% if (ViewData["Success"] != null) { %>
<div id="successMessage">
<%: ViewData["Success"] %>
</div>
<% } %>
MVC3:
#if (ViewData["Success"] != null) {
<div id="successMessage">
#ViewData["Success"]
</div>
#}
I used this approach in my last project in order to make the information returned from the server unobtrusive. Checking whether ViewData["Success"] or ViewData["Failure"] are done in the Master page, the divs are formatted using CSS, jQuery code was used to hide the notifications after 5 seconds.
Regards,
Huske
public ActionResult UploadPropertyImage()
{
// Business logic....
return Content("<script language='javascript' type='text/javascript'>alert('Save Successfully');</script>");
}
Basically that depends on how are you inserting the value into the database, as you would need a method to tells you whether the insertion was successful. As there's a few ways to do that now, linq/entity framework/sql/etc.
Then after you know whether did the insertion happens, then you can just assign a value to a variable and then from the code/aspx just check the value and do a simple alert.
<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function(){
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= bInsertSuccess %>";
if(bSuccess){
alert("Successfully Inserted");
}
});
</script>
You may add below code to tell user
Return Content("Data added successfully");
Related
I'm an MVC noob so bear with me, I'm used to working with web forms. I have a page where administrators can view all users. Right now it shows ALL users, inactive and active. I can make it show only active users by default, but I would like to have a checkbox that can be clicked in order to show inactive users. I want the change to occur as soon as the box is checked or unchecked.
In the view:
#Html.CheckBox("ShowInactive") <label for="inactvCheckBox">Show Inactive Users</label>
In the controller:
public ActionResult Index(bool ShowInactive)
{
var users = (ShowInactive) ? db.Users.OrderBy(u => u.LastName) :
db.Users.Where(u => u.Active == 1).OrderBy(u => u.LastName);
return View(users.ToList());
}
Obviously the way I'm doing it doesn't work, but I'm not sure what I'm missing. Index isn't receiving the value of ShowInactive and I get a null parameter entry error.
EDIT: apparently I need some javascript to handle the click event, and then pass the checkbox state to the controller; I guess I thought it would automatically link with the parameter name being the same. I tried adding the following javascript below, but it doesn't work. Again, I've probably written it wrong but my Google-fu is failing.
<script type="text/javascript">
$(document).ready(function () {
$('#ShowInactive').change(function () {
$("form").attr("Index", "/User/Index");
$("form").submit();
});
});
</script>
Alright, I figured it out. I didn't actually need to handle anything through the controller, I just loaded all users to the list and then added a hidden class to users who weren't active. Then upon checkbox click I toggled the hidden rows using javascript. It's quicker than reloading the view every time I click the checkbox. Only problem is it messes up alternating row colors when inactive users are hidden, but this page is only looked at by site admins so no big deal.
Controller:
public ActionResult Index()
{
var users = db.Users.OrderBy(u => u.LastName);
return View(users.ToList());
}
View:
#Html.CheckBox("ShowInactive", false, new { id = "ShowInactive" }) <label>Show Inactive Users</label>
[...]
#foreach (var item in Model.OrderBy(u => u.LastName).ThenBy(u => u.FirstName))
{
<tr #if(item.Active != 1) { <text>class="inactive hidden"</text>}>
[row data stuff]
</tr>
}
Javascript in view:
<script type="text/javascript">
$(document).ready(function () {
$('#ShowInactive').change(function () {
$(".inactive").toggleClass("hidden");
});
});
</script>
Change the checkbox to:
#Html.CheckBox("ShowInactv")
Thereby matching the parameter of your Action.
I am using MVC3, Razor and C#.
I have implemented a simple and robust inline editing solution for a grid.
Basically I use Razor to build my form which encloses the grid, and then the row that matches the item id gets opened up as the editable row which is coded as a partial View.
The Grid View (part):
#using (Html.BeginForm("Edit", "GridTest"))
{
<table>
<tr>
<th>col1</th>
<th>Col2</th>
</tr>
#{
foreach (var item in Model)
{
<tr>
#{
if ((Model.ItemId == item.Id))
{
Html.RenderPartial("_EditRow", item);
}
else
{
Html.RenderPartial("_DisplayRow", item);
}
}
</tr>
}
</table
}
EditRow.cshtml
#Html.TextBoxFor(p=>p.Name)
Save
Cancel
#Html.HiddenFor(p=>p.Id)
DisplayRow.cshtml
<td>
#Model.Name
</td>
<td>
#Html.ActionLink("Edit", "Edit", "GridTest", new {id = Model.Id}, null)
</td>
GridTest/Edit Action
public ActionResult Edit(int id)
{
var myRecord = db.Orders.First(p => p.Id == id);
return View("Index",myRecord);
}
GridTest/Edit Post Action
[HttpPost]
public ActionResult Edit(Order myRecord, string btn="")
{
if (btn == "Save")
{
if (ModelState.IsValid)
{
Order myCurrentRecord = db.Order.First(p => p.Id == myRecord.Id);
myCurrentRecord.Name = myRecord.Name;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(myRecord);
}
else
{
return RedirectToAction("Index");
}
The above code shows the design. It works greats and is simple. However it causes a postback of the complete page, and I would like to stop this "flashiness". So I suspect I need to somehow tweak the above code such that the "EditRow" posts inline, without refreshing the entire page. I suspect I am looking at using Ajax?
So how can the above code be simply upgraded to prevent complete page refresh, but rather row refresh?
Many thanks in advance.
At its simplest, you can probably just capture the submit event of the form and serialize that form to an AJAX POST. Something like this:
$('form').submit(function () {
$.post('#Url.Action("Edit", "GridTest")', $('form').serialize())
.done(function(data) {
// AJAX call is complete
// do something on the page?
});
return false;
});
This will use the same controller action in the same way that the form does, just via AJAX. The controller action will also respond the same way, which probably isn't what you want with an AJAX request. You might instead want to return some JSON data to indicate success, error conditions, results of server-side processing, etc. Something as simple as this can just indicate success from the controller action:
return Json(true);
You can, of course, return any structured data by passing it to Json(), which will serialize it to JSON data as the data value in the JavaScript done handler.
Edit: If you want to replace a piece of the client-side content wholesale with a partial view, you can still return that partial view in the AJAX request. The controller action can do something like this:
return PartialView("_DisplayRow", myRecord);
(Assuming myRecord is the type that is bound to that partial view.)
Then you'd have something for the done handler in the client-side code. Maybe something like this:
$('tr.someClass').html(data);
The idea here is that the tr element which is the "edit row" should be uniquely identified in some way (I'm using a class in my selector at the moment, but you can use whatever works for you), and its contents should be replaced with the contents of the partial view being returned from the server-side code.
I am using asp.net MVC2. i am facing a problem in state management of javascript contents.
i have got a image map in which on click on various part of image i am showing same page (redirect with parameters) with some parameter like : Secure/BodyWork?view=7
and on basis of value in parameter view i am showing various content on page. in that content i have got some checkboxes which i make checked and show it on left side in a div (checked one).
the issue is when i click on another part of image (of image map) it rediect me to same page with different "view=?" value but i loos state of my current divs(which contains name of checked check box of previous page).
my inherites line is like this:
Inherits="System.Web.Mvc.ViewPage<List<WBAC.Models.BodyWorkModel>>"
controller contains:
public ActionResult BodyWork(string view)
{
SecureModelService service = new SecureModelService();
return View(service.ListBodyWork(view));
}
[HttpPost]
public ActionResult BodyWork(BodyWorkModel model1)
{
//some code
}
i have tried with hidden field so in which i placed names of current page's checkbox but of course those loses value when i click on image map because of redirection of page to current page.
i have also tried with using ajax.beginform but its also not working because we are redirecting the page (to same page with different parameters like: view=3/view = 4) on click of image map.
please suggest me what should i change and how to do it.
Thanks
code in target div:
<div class="damageAreaMid" id="dvdamageAreaMid">
<% foreach (var item in Model)
{ %>
<div class="area">
<h2>
<%: item.Component %></h2>
<% Html.RenderPartial("~/Views/Shared/UCWorkArea.ascx", item.VehicleOption(item.ComponentID, item.Component));%>
</div>
<% } %>
</div>
You could use AJAX and refresh only the part of the page that needs to be refreshed.
public ActionResult BodyWork(string view)
{
SecureModelService service = new SecureModelService();
return View(service.ListBodyWork(view));
}
public ActionResult BodyWork(BodyWorkModel model)
{
//some code
return PartialView(model);
}
And in your view AJAXify the links on the image map:
$(function() {
$('#somecontainer a').click(function() {
$('#someresultcontainer').load(this.href);
return false;
});
});
ASP.NET MVC
I have one page Index.aspx where I'm loading two usercontrols into divs. This is working fine. For the moment the usercontrols just shows data and thats working fine. But now I want to add a delete function in the usercontrols and then refresh the div in the Index.aspx page. Is this possible?
Index.aspx
<!-- Panel One -->
<div id="panel1">
<img src="/Content/ajax-loader.gif" alt="Loading..." />
</div>
<script type="text/javascript">
$('#panel1').load('../Reports/ReportOne')
</script>
<!-- Panel Two -->
<div id="panel2">
<img src="/Content/ajax-loader.gif" alt="Loading..." />
</div>
<script type="text/javascript">
$('#panel2').load('../Reports/ReportTwo')
</script>
ReportOne.ascx and ReportTwo
Just listing some data with a foreach. Here I want to add a deletebutton for each item in the lists.
Make your "delete" action into something like this:
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Delete(int id) {
try {
// do what ever here in deleting the record etc
// ...
return null;
} catch (Exception ex) {
TempData[TempDataKeys.ErrorMessage] = "Error in deleting: " + ex.Message;
return RedirectToAction("List");
}
}
In you ascx/aspx, create a jQuery method to wrap your ajax call to the controller:
function deleteRecord(recordId) {
if (confirm("Are you sure that you want to delete this record?")) {
var token = $("input[name='__RequestVerificationToken']")[0].value;
url = '<%= Url.Action("Delete", "MyController") %>';
$.post(
url,
{ id: recordId, __RequestVerificationToken: token },
function(data) {
if (!data == "") {
// success - reload/refresh panel control
$('#panel1').load('../Reports/ReportOne');
} else {
// failed - handle error
}
}
);
}
}
You will need to put your AntiForgeryToken appropriately so the script can access it - you only need 1 for the whole page. Your delete link should then call to the javascript, instead of to the action in the controller directly:
Delete
When the user clicks on the delete button inside the user control you could invoke an action that will delete the necessary information from the database and return a partial view refreshing the control. So put a delete link inside the control:
<%= Html.ActionLink("Delete", "DeleteReportOne", null, new { id = "deleteReportOne" }) %>
and then inside the main page register the click callback for this link:
$(function() {
$('#deleteReportOne').click(function() {
$('#panel1').load(this.href);
});
});
You may use JQuery UI tabs to add and remove the content from the page
JQuery UI Manipulate tabs
JQuery Tabs and ASP.NET MVC Partial Views
you need to modify your user controls
I have a partial view which has a Ajax.BeginForm, with a UpdateTargetID set. When the validation on the form fails the update target id is replaced with the validation errors, but when there are no validation errors users should be redirected to a new page.
The code in my Partial view is
<div id="div_UID">
<% using (Ajax.BeginForm("FindChildByUID", new AjaxOptions { UpdateTargetId = "div_UID" } ))
{%>
<p>
<label>UID:</label>
<%= Html.TextBox("UID") %>
</p>
<input type="submit" value="Continue" />
<% } %>
</div>
</pre>
The code in my controller is as follows
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FindChildByUID(Student student)
{
Student matchingStudent = _studentService.FindChildByUID(student.UID);
if (matchingStudent == null)
{
ModelState.AddModelError("UID", String.Format("No matching child found for the entered UID: {0}", student.UID));
return PartialView();
}
else
{
// full view
return RedirectToAction("ConfirmChildDetails", matchingStudent);
}
}
So, for I have been unsuccessful to display the full view on it's own, as it always seems to dipslay the full view in the UpdateTargetID div specfied in the Ajax.BeginForm.
Any suggestions on how I can get this to work?
Thanks
What your AJAX post is doing is making a request and waiting on a response that contains html to input onto the page. The configuration is such that whatever html is returned will be injected into the div you've named "div_UID".
I typically avoid scenarios like this and use traditional posting if a redirect is required upon a successful outcome of the POST.
I imagine you could do it like this using jQuery to submit rather than the Ajax.BeginForm (or just set a callback function for your Ajax.BeginForm):
function SubmitForm(form) {
$(form).ajaxSubmit({ target: "#div_to_update", success: CheckValidity });
}
function CheckValidity(responseText) {
var value = $("#did_process_succeed").val();
if (value == "True") {
window.location.replace("url_of_new_action_here");
}
}
You just have to have a hidden field in your partial view called "did_process_succeed" and set the value of True or False based on some logic in your controller.
There are likely other ways as well. Perhaps someone else will chime in. I hope this helps for now.