Showing message box (alert) after submitig form - javascript

I have form in asp.net mvc
I want to show a alert message when user submit a form.
public ActionResult AddMessage(Message message)
{
If(ModelState.IsValid)
{
db.Messages.Add(message);
db.SaveChanges();
return RedirectToAction(“Index”);
}
else
{
return View();
}
}

The alert method is a JavaScript method which needs to be executed on client side, by the browser.
Since you are doing a normal form submit and you want to show the alert when ModelState.IsValid is true, you have to do that inside the view returned by index action.
You can use TempData to pass some data between your current action method code and the action method/view rendered by a redirect response.
public ActionResult AddMessage(Message message)
{
If(ModelState.IsValid)
{
db.Messages.Add(message);
db.SaveChanges();
TempData["Message"] = "Saved successfully";
return RedirectToAction(“Index”);
}
else
{
return View();
}
}
and in the view returned by Index action, you can check TempData["Message"] exist and if yes, read it and show it in an alert.
#section Scripts
{
<script>
#if(TempData["Message"]!=null)
{
#:alert("#TempData["Message"]");
}
</script>
}

Related

How to get data flag from controller to jsp in Spring mvc, after executing all code from controller

This is my controller code.
#RequestMapping(value={VspCommonConstants.INTERVIEW_PANEL_MANAGER_URL+"/submitAssessmentform"}, method = RequestMethod.POST)
public String submitAssessmentform(HttpServletRequest request,Model model) throws JsonParseException, JsonMappingException, IOException
{
boolean saveFlag=false;
try {
saveFlag = interviewQuestionResultService.saveInterviewQuestionRemark(actualData, list,new Long(Appid),new Long(uInfo.getId()),existFlag,
VspCommonConstants.getIpFromRequest(request),new Long(uInfo.getId()));
} catch (Exception e) {
saveFlag=false;
}
model.addAttribute("saveFlag",saveFlag);
return view;
}
At jsp i'm taking 'saveFlag' in document.ready function as follows
$(document).ready(function() {
var saveFlagValue = $("#saveFlag").val();
alert("saveflag:"+saveFlagValue);
if(saveFlagValue == "true"){
/* swal("Error","Data saved successfully .","error"); */
swal({
html : true,
title : '<i></i>',
text : '<b>Data saved successfully.</b>'
});
}
});
Now i wanted to have this saveFlag only after controller executes its all code. But unfortunitely im getting the data when my page get loaded. and i want this saveFlag when form is submitted and get response from controller, not at starting. Please help me solve the problem. Thank you.
In the JSP, you should wrap your jQuery code into this tag :
<c:if test="${not empty saveFlag}">
<script type="text/javascript">
$(document).ready(function() {...}
</script>
</c:if>
When the user first arrive on the page, the saveFlag is empty since the controller has not been called. In consequences, the jQuery code won't be executed. But when the form is submitted, the saveFlag is will be true or false and success / error message will be displayed.

Page is not refreshed by calling RedirectToAction

In the View I have a linked button and there is java scripts to collect information from view and then post to the corresponding action 'GroupDeny'
#Html.ActionLink("Deny Selected", "GroupDeny", null, new { #class = "denySelectedLink" })
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).on('click', '.denySelectedLink', function (e) {
//Cancel original submission
e.preventDefault();
var identifiers = new Array();
//build the identifiers . . .
var jsonArg = JSON.stringify(identifiers);
$.post('/LicenseAssignment/GroupDeny?licensePermissionIdentifiers=' + encodeURIComponent(jsonArg));
});
</script>
Then in the controller, the GroupDeny will update the DB and then
call RedirecToAction in order to refresh the view
public class LicenseAssignmentController : Controller
{
[HttpPost]
public ActionResult GroupDeny(string licensePermissionIdentifiers)
{
// changes the DB
return RedirectToAction("Index");
}
// GET:
public async Task<ActionResult> Index()
{
var model = get data from DB
return View(model);
}
Everything seems work as expected, The Index will be called after the RedirectToAction("Index") is executed, and the model is update to date their when I watch it during debugging, the only problem is that the page is not refreshed at all, that is to say the view still keep unchanged, but after I refresh the page manually (press F5), the data will be updated with the values from DB
We use AJAX when we don't want to navigate away from the page. Your $.post() is an AJAX request.
Since you want navigation add a form to your page
#using(Html.BeginForm("GroupDeny", "LicenseAssignment", FormMethod.Post))
{
<input type="hidden" value=""
name="licensePermissionIdentifiers"
id="licensePermissionIdentifiers" />
}
Now submitting this form will navigate
$(document).on('click', '.denySelectedLink', function (e) {
e.preventDefault(); // prevent link navigation
var identifiers = new Array();
//build the identifiers . .
// populate the form values
$("#licensePermissionIdentifiers").val(identifiers);
$("form").submit();
});
The RedirectToAction() returns to the browser a 302 Redirect to LicenseAssignment/Index then you hit the Index action.
Since you are using Ajax you will have to redirect on the return of your $.post call and change your GroupDeny to a JsonResult.
Something like this maybe:
JS
$.post('/LicenseAssignment/GroupDeny?licensePermissionIdentifiers=' + encodeURIComponent(jsonArg), function(data){
if(data.Success){
//redirect
window.location.reload();
}else{
//handle error
}
});
Controller Action
[HttpPost]
public JsonResult GroupDeny(string licensePermissionIdentifiers)
{
// changes the DB
return Json(new { Success = true });
}

Can I send a message instead of a view back as an ActionResult with ASP.NET MVC4

I have the following action in ASP.NET MVC4
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
// ?? Need some code here
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
I have the following code that calls this:
$('#article').on('submit', '#loginForm, #registerForm', function (e) {
e.preventDefault();
var $form = $(this);
var href= $form.attr('data-href');
$form.validate();
if (!$form.valid()) {
return false;
}
var data = $form.serializeArray();
$.ajax(
{
data: data,
type: 'POST',
url: href
})
.done(submitDone)
.fail(submitFail);
function submitDone(content) {
$('#article').html(content)
}
function submitFail() {
alert("Failed");
}
return false;
});
If the registration works I would like to force the whole web page to refresh. Is there
a way that I can send back a message from the actionmethod to the javascript to
tell it that the registration works and the javascript should refresh the whole
web page?
I did try return RedirectToLocal("/"); but this definitely does not work. What
this does is to return a new page and then have it populated in the #article DIV.
There is nothing that will automatically refresh the browser from the server.
To refresh the browser from the server you'll need to send something from the server to the client indicating that you want to refresh the page. You'll need to write the javascript to look for the indication to refresh the browser.
Client Code
function submitDone(content) {
var json = $.parseJson(content);
if(json.isSuccess) {
//Do something here
}
$('#article').html(json.content)
}
Server code
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
// ?? Need some code here
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return Json(new {isSuccess = true, content = model});
}
I am unsure of what you are trying to accomplish by refreshing the page, if it's to clear out the form fields. The same could be achieved by using JavaScript. By using javascript instead of a page refresh you won't lose page state, such as error messages.
well i can think of a quick javascript trick to refresh a page on success like this
function submitDone(content) {
window.location.reload();
}
this will reload the page on the success.

Redirect From Partial View - PUBLISHED not working but DEVELOPING is OK

I have a javascript redirection in my logon controller that open my home page if login was successfull: return JavaScript("window.top.location ='" + returnUrl + "';")
My logon controller is called by a sumbit inside Ajax.BeginForm as a partial view.
While developing (F5 on my vs2010) my solution work perfect, but my published version (the one I upload to server) is not redering a full new view, instead it is refreshing the div in my targetid.
My Partial View Code
#model Web.Models.LogOnModel
<div id="LogBox2">
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "LogBox2", }))
{
<fieldset>...'All textbox capturing data here
<input type="submit" value="LogOn" />
</fieldset>
#Html.ValidationSummary(true, "Login was unsuccessful")
}
</div>
My Controller Code
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return JavaScript("location.href ='" + returnUrl + "';");
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
if (Request.IsAjaxRequest())
{
// If an ajax request was made return only the validation errors
// instead of the whole page
return PartialView("LogIn2");
}
else
{
return View();
}
}
I really dont understand why debugging (F5) works OK bur Published NOT. Do you?
Thanx in advance
Not sure whether I understand your scenario fully. I think your production is working as it should do; Consider the scenario: the form is being submitted through Ajax, and the 'returnUrl' is null/invalid then the div 'LogBox2' will be updated with the response of the action 'Home/Index' line return RedirectToAction("Index", "Home");
If your intention is to redirect the user to the path 'returnUrl' or the 'home/index' while log-in is successful, then one solution could be replacing the line
return RedirectToAction("Index", "Home");
with
return JavaScript("location.href =" + HttpUtility.JavaScriptStringEncode(Url.Action("Index", "Home"), true) + ";");
You can also consider using jQuery Ajax with ASP.NET MVC.

Inject something to ASP MVC Result

In my project I need to add functionality, that show infobox in right top corner of page, when client save something. Everything works fine when save operation do redirect to another page in my solution.
Client run save action:
[SaveAction] //my own action filter to show info box
public ActionResult Details(int id, FormCollection form)
{
var pojazd = PojazdRepo.GetById(id);;
if (UpdateAndSave(pojazd, form))
{
return RedirectToAction("Index");
}
else
{
return View(GetDetailsViewModel(id, true));
}
}
Now my action filter test that ModelState.IsValid is true then add something to TempData:
public class SaveActionAttribute : ActionFilterAttribute
{
private bool test;
private bool isAjax;
public override void OnActionExecuted(ActionExecutedContext ctx)
{
test = ctx.Controller.ViewData.ModelState.IsValid;
isAjax = ctx.HttpContext.Request.IsAjaxRequest();
base.OnActionExecuted(ctx);
}
public override void OnResultExecuting(ResultExecutingContext ctx)
{
if (test)
{
if (isAjax) ctx.Controller.TempData["ActionPopUp"] = "";
else ctx.Controller.TempData["ActionPopUp"] = "save";
}
base.OnResultExecuting(ctx);
}
}
And my Site.Master run script if TempData["ActionPopUp"] = "save":
<script type="text/javascript">
$(document).ready(function () {
var test = '<%: TempData["ActionPopUp"] %>';
if (test != '') SaveSuccessPopUp(test);
});
</script>
As mentioned, this solution works fine, when controller make Redirect and Site.Master is loaded again, my problem is, how to inject SaveSuccessPopUp() function to action result, when Action was called by AJAX and return something, what don't reload page and don't run Site.Master $(document).ready code block.
Nice question.
You need to probably work with partial view here. I mean if your request is an ajax request, append the TempData again and the TempData will be outputted inside the partial view.
How will you send that partial view output as chunk of html?
I have a blog post about how you can send the partial view as string. The topic is different but you will get the idea:
http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views
Here is an example:
[HttpPost]
public ActionResult toogleIsDone(int itemId) {
//Getting the item according to itemId param
var model = _entities.ToDoTBs.FirstOrDefault(x => x.ToDoItemID == itemId);
//toggling the IsDone property
model.IsDone = !model.IsDone;
//Making the change on the db and saving
ObjectStateEntry osmEntry = _entities.ObjectStateManager.GetObjectStateEntry(model);
osmEntry.ChangeState(EntityState.Modified);
_entities.SaveChanges();
var updatedModel = _entities.ToDoTBs;
//returning the new template as json result
return Json(new { data = this.RenderPartialViewToString("_ToDoDBListPartial", updatedModel) });
}
RenderPartialViewToString is a controller extension. you can find the the complete code for that from below link:
https://bitbucket.org/tugberk/tugberkug.mvc/src/6cc3d3d64721/TugberkUg.MVC/Helpers/ControllerExtensions.cs
After you have your html back on the client side code, append it you DOM and work on it. Animate it, show/hide it, do whatever you need with it

Categories