Presenting Modal After Form Submission in MVC - asp.net-mvc

I am trying to create a modal that will tell the user their submission was successfully submitted. This works fairly well, but the only problem is I have to declare each of my properties and assign it a value, then in the Json method I have accept all those parameters then do something with them. Is there any way to do this with a ViewModel? Or any otherway that this can be done using a ViewModel?
controller:
public Json Send(string var1, string var2)
{
...
if(valid)
return new Json(true, JsonRequestBehavior.AllowGet);
else
return new Json(false, JsonRequestBehavior.AllowGet);
}
javascript:
function submitData() {
$.ajax({
url: "/Report/Send",
type: "POST",
dataType: "json",
data: { var1 = Model.var1, var2 = Model.var2... },
success: function (data) {
if(data) {
showDialog();
}
else {
$("#errorDiv").load('Report/Error/');
}
},
error: function (somefunction) { }
});
}

Yes, create a ViewModel POCO class:
var myJsonResult = new { result: true };
return Json(myJsonResult);
You can also use a strongly typed ViewModel and return that:
var myJsonResult = new CustomResult { result: true };
return Json(myJsonResult);
Then just check that property on the class in your success function:
success: function (data) {
if(data.result) {
showDialog();
}
else if(!data.result) {
$("#errorDiv").load('Report/Error/');
}
},
EDIT:
You might also want to look at jquery's .serialize() method:
data: $("#myForm").serialize()
This will be useful if you bind your ViewModel to form elements and need to post them back to the server.

Related

Get Boolean Value and use it in Ajax call to controller

I have this javascript code to call a function from my controller that returns a boolean value
<script type="text/javascript">
$(function () {
$(document).ready(function NumberAmt() {
$.ajax({
url: 'CallCenter/CallCenterAmt',
type: 'Get',
contentType: 'application/json;',
success: function (data) {
}
});
})
});
I want to be able to use that boolean value in a function in the javascript on my page load to figure out what to display from my view. Please help Thanks
THis is the Controller Function it is calling
[HttpPost]
public ActionResult CallCenterAmt()
{
bool threeNumbers=false;
try
{
using (var entities = new OpenRoad.Data.Repository.OpenRoadEntities())
{
var CallCenterNumberAmt = (from c in entities.CallCenterNumberAmts
where c.SiteId == OpenRoad.Web.Session.SiteId
select c).FirstOrDefault();
if (CallCenterNumberAmt == null)
{
CallCenterNumberAmt = new Data.Repository.CallCenterNumberAmt();
CallCenterNumberAmt.SiteId = OpenRoad.Web.Session.SiteId;
CallCenterNumberAmt.ThreeNumbers = false;
entities.CallCenterNumberAmts.Add(CallCenterNumberAmt);
entities.SaveChanges();
}
else
{
if (CallCenterNumberAmt.ThreeNumbers == true)
{
threeNumbers= true;
}
else
threeNumbers= false;
}
}
}
catch
{
}
return Json(threeNumbers);
}
}
Your data should contain the value. You need to make sure you're actually returning JSON, then call it based on the variable
e.g. {YourVariable: true}
success: function(data) {
if(data.YourVariable) {
//true
}
}
Instead of the Controller method returning a boolean, have it return a JSON object containing a boolean instead.
i.e. { isOkay : true }
Then in your Ajax call, you can check to make sure that the controller returned what you thought it did by using data.hasOwnProperty("isOkay") and then using the value of isOkay to determine whatever else you need to.

.ajax get keep data keep coming null in controller

I am trying to use this following function to get some data.
function SaveData() {
var value = $('#tblRadio').find('input[type="radio"]:checked').val();
$.ajax({
type: "POST",
url: '/home/IsEmployeeVoted',
success: function (result) {
alert(result); // shows whole dom
if (parseInt(result) > 0) {
$('div.dvVoteWrapper').removeAttr('style');
$('div.popupArea').removeAttr('style');
}
else {
window.location = '/home/EmployeeVote?regoinID='+ value;
}
},
error: function () {
alert("Sorry, The requested property could not be found.");
}
});
}
The controller function:
public ActionResult EmployeeVote(string regionID)
{
}
regionId keep coming null to me though the value variable have some value in javascript. any ideas ??
Change
data: 'regionID=' + value,
to
data: {regionID: value},
You need to pass the data as an object literal. Another option (which I dont recommend), which is closer to your idea:
url: '/home/IsEmployeeVoted?regoinID=' + value,
But if you want this to work you would need to remove the type: 'POST' (since GET is the default type).
Few issues:
var value = $('#tblRadio').find('input[type="radio"]:checked').val();
I'd make sure that value is not undefined/null.
use alert(value) before the ajax call.
Also you are specifying GET but POSTING data to the server.
You could also wrap the regionId inside a javascript object, for instance.
$.ajax({
type: "POST",
data: { regionID: value },
url: '/home/IsEmployeeVoted',
success: function (data) {
alert(data); // shows whole dom
if (parseInt(data) > 0) {
$('div.dvVoteWrapper').removeAttr('style');
$('div.popupArea').removeAttr('style');
}
else {
window.location = "/home/EmployeeVote";
}
},
error: function () {
alert("Sorry, The requested property could not be found.");
}
});

How to bind the value in client side using ajax and mvc

I need to bind the value in html list box. But ajax and return the value in client side. but it has the proper rerun value. I think Its return format is wrong. How to change this? My code is given below
public ActionResult value(bool sta1, bool sta2)
{
// my code
return Json(Selectedstudents.ToList(), JsonRequestBehavior.AllowGet);
}
ajax:
$.ajax({
//my code
dataType: 'json',
success: function (data) { // not trigger here
// my code
}
});
$.ajax ( {
url : "/ControllerName/Value"
type: 'Get'
data : { val1 : value1, val2:value2 }
datatype: 'json'
success : function(data) {
$("#listboxid").html(data);
do something...
}
});
and in controller
public JsonResult value(bool val1, bool val2)
{
// my code
result.Data = Selectedstudents.ToList();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}

Ajax call within JSTree bind on "create.jstree" for contextmenu is not working

Everything seems correct in my $.ajax call within the .bind on create.jstree. However, the call to the controller (I'm using MVC 3) is not occurring for some reason. I put a breakpoint on the POST function that's referenced by the ajax call, but it never even gets called. Which leads me to believe that there's something wrong with the combination of the bind and ajax call that is preventing the post function from ever being called. I would appreciate the advice.
jstree code:
$("#RequirementsTree")
.bind("select_node.jstree", function(event, data) {
if(is_requirement_node(data))
{
var id = data.rslt.obj.attr("id");
if(id != null)
{
$("#RequirementsTree").jstree('close_all')
}
else {
alert("Requirement node select error");
}
}
})
.bind("create.jstree", function(e, data) {
alert(data.rslt.obj.text());
alert(ParentNode);
// Ajax call to Server with parent node id and new node text
debugger;
$.ajax({
type: "POST",
url: function(node) {
return "/RMS/insertRequirementNode";
},
data: {
ParentID : ParentNode,
ChildNodeText : data.rslt.obj.text()
},
success: function(new_data) {
return new_data;
}
});
ParentNode = null;
if (data.rslt.parent == -1) {
alert("Can not create new root directory");
// Rollback/delete the newly created node
$.jstree.rollback(data.rlbk);
return;
}
BranchReqFLag = null;
}).jstree({
json_data: {
data: RBSTreeModel,
ajax: {
type: "POST",
data: function (n) {
return {
NodeID: n.attr("id").substring(4),
Level: n.attr("name").substring(7)
};
},
url: function (node) {
return "/Audit/GetRequirementsTreeStructure";
},
success: function (new_data) {
return new_data;
}
}
},
contextmenu: {
items: function($node) {
return {
createItem : {
"label" : "Create New Branch",
"action" : function(obj) { this.create(obj); BranchReqFlag = "Branch"; ParentNode = obj.attr("id").substring(4);}
},
renameItem : {
"label" : "Rename Branch",
"action" : function(obj) { this.rename(obj);}
}
};
}
},
plugins: ["themes", "json_data", "ui", "crrm", "contextmenu"]
});
Controller POST function:
[AllowAnonymous]
[HttpPost]
public int insertRequirementNode(int ParentID, string ChildNodeText)
{
RBSText CurrNode = new RBSText();
int CurrentNodeID = -1;
//CurrNode.RMSHierarchyText = ChildNodeText;
using (Contract ActiveContract = getContract())
{
try
{
// Inserts the new node beneath the Parent Node
CurrentNodeID = ActiveContract.CreateRMSNode(CurrNode, ActiveContract.ContractId, ActiveContract.user_id, 2, "Child");
}
catch (Exception ex)
{
throw ex;
}
}
return CurrentNodeID;
}
The URL specified in your $.ajax() function is likely wrong. Use #Url.Content() along with the the Server Root Wildcard: ~ to prefix your URL , so your URL always refers to the correct server root path no matter how your application is deployed, this assuming that you are setting up your jstree in a Razor View so you have access to the Razor Engine:
$.ajax({
type: "POST",
url: "#Url.Content("~/RMS/insertRequirementNode")",
data: {
ParentID : ParentNode,
ChildNodeText : data.rslt.obj.text()
},
success: function(new_data) {
return new_data;
}
});
If you are setting up jstree in a .js file, then you need to store the server root in a javascript variable defined in a Razor View first and refer to that variable instead.

How handle different results in an ajax call?

Suppose you have the following controller action
[HttpPost]
public ActionResult Save( CustomerModel model )
{
if (!ModelState.IsValid) {
//Invalid - redisplay form with errors
return PartialView("Customer", model);
}
try {
//
// ...code to save the customer here...
//
return PartialView( "ActionCompleted" );
}
catch ( Exception ex ) {
ActionErrorModel aem = new ActionErrorModel() {
Message = ex.Message
};
return PartialView( "ActionError", aem );
}
}
And suppose you call this action using jQuery:
$.ajax({
type: "post",
dataType: "html",
url: "/Customer/Save",
sync: true,
data: $("#customerForm").serialize(),
success: function(response) {
/*
??????
*/
},
error: function(response) {
}
});
I would like to be able to distinguish between the results I am getting to handle them in different ways on the client. In other words how can I understand that the action
returned the same model because has not passed validation
returned one of the views that represents error info/messages
Any suggestion?
One way to handle this is to append a custom HTTP header to indicate in which case we are falling:
[HttpPost]
public ActionResult Save( CustomerModel model )
{
if (!ModelState.IsValid) {
//Invalid - redisplay form with errors
Response.AppendHeader("MyStatus", "case 1");
return PartialView("Customer", model);
}
try {
//
// ...code to save the customer here...
//
Response.AppendHeader("MyStatus", "case 2");
return PartialView( "ActionCompleted" );
}
catch ( Exception ex ) {
ActionErrorModel aem = new ActionErrorModel() {
Message = ex.Message
};
Response.AppendHeader("MyStatus", "case 3");
return PartialView( "ActionError", aem );
}
}
And on the client side test this header:
success: function (response, status, xml) {
var myStatus = xml.getResponseHeader('MyStatus');
// Now test the value of MyStatus to determine in which case we are
}
The benefit of this is that the custom HTTP header will always be set in the response no matter what content type you've returned. It will also work with JSON, XML, ...
Remark 1: To avoid cluttering you controller action with all those Response.AppendHeader instructions you could write a custom ActionResult allowing you to directly specify the value of this header so that you simply return this.MyPartialView("Customer", model, "case 1")
Remark 2: Remove this sync: true attribute from the request because it makes my eyes hurt (in fact I think you meant async: 'false').
You could check for an element unique to that view, for example:
$.ajax({
type: "post",
dataType: "html",
url: "/Customer/Save",
sync: true,
data: $("#customerForm").serialize(),
success: function(response) {
var resp = $(response);
if($(resp.find("#customer").length) {
//customer returned
} else if($(resp.find("#completed").length) {
//completed view
} else if($(resp.find("#error").length) {
//error view
}
},
error: function(response) {
}
});

Resources