How to access viewbag value in AJAX success? - c#

Here I EditMyProfile method which is used to edit the customer detail.
In this method I am trying to set ViewBag.msg = 1 and return return PartialView("MyProfile", getCusomerDetail);, set ViewBag.msg = 0; and return return PartialView("EditMyProfile", customer); and using that ViewBag.msg value want put condition on AJAX success whether to show success message or not.
Now, the problem is that even though the ViewBag.msg has value in EditMyProfile view, the var message = '#ViewBag.msg' gives var message = "" in AJAX success.Any help with my code will be a great help
Thank you
Below is my AJAX
<script>
$(document).ready(function () {
$("#EditMyProfileCreate").submit(function (ev) {
debugger;
ev.stopImmediatePropagation();
var Action = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: Action,
type: 'POST',
data: formData,
async: false,
success: function (data) {
debugger
var message = '#ViewBag.msg'; // Here the var message = "" even though #ViewBag.msg' has value
if (message == "1") {
swal("Congratulations!", "Chages saved successfully", "success");
$("section#myAccountMainDiv").html(data);
}
else {
$("section#myAccountMainDiv").html(data);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
})
Below is my
[HttpPost]
public ActionResult EditMyProfile(CustomerVM customer)
{
if (ModelState.IsValid)
{
using (emedicineEntities _db = new emedicineEntities())
{
var getCustomer = _db.Customers.Where(x => x.CustomerId == customer.CustomerId).FirstOrDefault();
getCustomer.CustomerName = customer.CustomerName;
getCustomer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
getCustomer.CustomerEmail = customer.CustomerEmail;
getCustomer.CustomerAddress = customer.CustomerAddress;
getCustomer.ConfirmPassword = getCustomer.PasswordHash;
_db.Entry(getCustomer).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.msg = 1; // here ViewBag.msg is set 1 on successfull edit
var getId = Global.CustomerId;
var getCusomerDetail = _db.Customers.Where(x => x.CustomerId == getId).FirstOrDefault();
return PartialView("MyProfile", getCusomerDetail);
}
}
else
{
ViewBag.msg = 0; // here ViewBag.msg is set 0 when model is invalid
return PartialView("EditMyProfile", customer);
}
}

To Access ViewBag dictionary in javascript, your Javascript code block must be on the cshtml file and not in the external javascript file.
In Controlller
public ActionResult Index()
{
ViewBag.Data = "haha";
return View();
}
In cshtml file
<script>
$(document).ready(function () {
alert('#ViewBag.Data');
});
</script>
As you are calling your controller through an Ajax call, you need to return the data as a variable inside your partial view. What i would suggest is to create a hidden field inside your partial view's cshtml file and assign that the value of ViewBag property at compile time. Then inside success function get the value of hidden field and compare.

Related

MVC and JQuery Load parameter List

I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all

Refresh MVC Dropdownlist

I'd like to refresh an MVC Dropdownlist from a JsonResult method.
Here's the public method that returns the result:
[HttpPost]
[ValidateAntiForgeryToken]
[CustomAuthorize]
public JsonResult GetHtmlApplicationSelectionList()
{
try
{
List<SelectListItem> applicationList = new List<SelectListItem>();
SelectListItem defaultApplicationValue = new SelectListItem();
defaultApplicationValue.Value = "0";
defaultApplicationValue.Text = "-- Select Application --";
defaultApplicationValue.Selected = true;
applicationList.Add(defaultApplicationValue);
foreach (var app in businessLogic.GetApplications().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Name }))
{
applicationList.Add(app);
}
return Json(new { result = "success", list = applicationList }, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(new { result = "failure", message=ex.Message}, JsonRequestBehavior.AllowGet);
}
}
And here's the jQuery function that calls the POST method to get the updated list of applications:
function UpdateApplicationList() {
$.ajax({
url: 'Global/GetHtmlApplicationSelectionList',
type: 'POST',
dataType: 'json',
success: function (data) {
$('.applicationSelector').html('');
$('.applicationSelector').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
}
How can I force the $(.applicationSelector') dropdownlist to contain the new list without having to loop through the list retured as JSON? Is it possible to return the html of the list( applicationList) and just refresh the html using
$('.applicationSelector').html(data); ?
You need to append an <option> for each item.
This is the answer taken from this post which provides a pretty simple and straight forward example.
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
Where var selectValues is your JSON list

Returning either a Partial View or a View

From my Home page i have a search textbox that when search is clicked calls an ajax search function which calls my controller. Based on the searchString that is passed I want to either replace a div with a gridview (this part is working) or have it load a new page. Instead it is loading the new view in the same div that the partial views are replacing. How can I do this? Ill post my code below.
All my data is coming back correctly and everything else is working just fine.
<script>
$(function () {
$('.search').click(function () {
var $buttonClicked = $(this);
var searchString = $("#searchStringTextBox").val();
$.ajax({
url: '#Url.Action("ShowGrids")',
type: 'GET',
data: { searchString: searchString },
modal: true,
success: function (partialView) {
$('#gridViews').html(partialView);
$('#gridViews').show();
}
});
});
});
</script>
controller
public ActionResult ShowGrids(string searchString)
{
if (IsValidPersonIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var x = Convert.ToInt64(id);
var model = cs.GetById(x);
TempData["model"] = model;
return Redirect(Url.Action("ShowPersonDetails", "Data"));
}
else if(IsValidIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var model = ps.GetById(Convert.ToInt64(id));
return View("Details", model);
}
else if (IsValidServiceIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var model = vss.GetById(Convert.ToInt64(id));
return PartialView("ServiceDetails", model);
}
}
public ActionResult ShowPersonDetails()
{
var model = TempData["model"];
return View("PersonDetails", model);
}
This has every way I tried to get it to work. Just figured I would show what I was trying and it not working.
The if on server-side is not affecting what the javascript does on success: it's stuffing the results of the call into a div.
If that's not what you want to do, you need to test for the results in javascript and do something else if what you got is not a partial view.
You can do something like this. This is not fully tested.
public JsonResult ShowGrids(string searchString)
{
if (IsValidPersonIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var x = Convert.ToInt64(id);
var model = cs.GetById(x);
TempData["model"] = model;
return Json(new { IsRedirect = true, RedirectUrl = Url.Action("ShowPersonDetails", "Data") }, JsonRequestBehavior.AllowGet);
}
else if(IsValidIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var model = ps.GetById(Convert.ToInt64(id));
return Json(new { IsRedirect = false, Content = RenderRazorViewToString("Details", model) }, JsonRequestBehavior.AllowGet);
}
else if (IsValidServiceIdFormat(searchString))
{
var id = searchString.Substring(1);
id = id.Replace("-", "");
var model = vss.GetById(Convert.ToInt64(id));
return Json(new { IsRedirect = false, Content = RenderRazorViewToString("ServiceDetails", model) }, JsonRequestBehavior.AllowGet);
}
}
<script>
$(function () {
$('.search').click(function () {
var $buttonClicked = $(this);
var searchString = $("#searchStringTextBox").val();
$.ajax({
url: '#Url.Action("ShowGrids")',
type: 'GET',
data: { searchString: searchString },
modal: true,
success: function (data) {
if(data.IsRedirect){
window.location.href = data.RedirectUrl;
}
else{
$('#gridViews').html(data.Content);
$('#gridViews').show();
}
}
});
});
});
</script>
Code for rendering view to string:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
make sure when ever you call action using jQuery, action will return HTML string into jQuery, if you want to redirect than return some json string from your action to jQuery call and redirect page from there

jquery.POST to MVC controller to return JSON

I have created a following model
public class myModel
{
public int ID;
public string Name;
public int[] days;
}
Then I created an action in a controller
[HttpPost]
public ActionResult myCtrlAction(myModel thisModel)
{
if (ModelState.IsValid)
{
return Json(thisModel);
}
else
{
string errorMessage = "<div class=\"validation-summary-errors\">"
+ "The following errors occurred:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li class=\"field-validation-error\">"
+ error.ErrorMessage + "</li>";
}
}
errorMessage += "</ul>";
return Json(new myModel { Name = errorMessage }); //just for now
}
}
In my javascript I send the data using jQuery.post() as
$("#myBtn").click(function () {
var mydata = {
ID: $("#inputID").val(),
Name: $("#inputName").val(),
Days: $("#selectDays").select2("val")
}
var url = 'myController/myCtrlAction'; //definitly it was writtern as #Url.Action
$.post(url, mydata, function(data) { alert(data); //which shows [object object]
}, 'json');
});
Now On request when I debug in Chrome I saw in headers as
Form Data
ID: 5
Name: SomeName
Days[]: 6
Days[]: 5
In Response I got json format of my model as
{ID: "0", Name: "null", Days: "null"} it means my model state is valid but why its not having the values?
Any body has any idea. what I did wrong or do I miss something?
I think your model's data is not set thus you get null values on Chrome.
If your javascript does not have a typo (and that you only made a typo when creating the question, then try this in your method myCtrlAction;
First try create getters and setters for your fields in myModel. Then;
replace;
errorMessage += "</ul>";
return Json(new myModel { Name = errorMessage }); //just for now
with this;
myModel myMODTest= new myModel();
myMODTest.setID(1111);
myMODTest.setName("testName");
myMODTest.setDays({1,2,3});
return Json(myMODTest); //just for now
See if you get on your browser the following;
{ID: "1111", Name: "testName", Days: "{1,2,3}"}
I do this following:
1: JavaScript: When clicking the button: Serialize the form-data and send it to the Controller:
function ajaxSubmitEditSupplierQuote() {
var formData = $("#SupplierQuoteEditForm").serializeArray();
$.ajax({
type: "POST",
url: '#Url.Action("Edit", "SupplierQuote")',
data: formData,
dataType: "json",
cache: false,
success: function (data1) {
// Here I create then a new Url-string.
// Simple access your Json Data, as you have named it in the return of the Controller-Action.
var strUrl = "/Equipment/" + data1.target.toString();
// ...
//
// ...
}
});
}
2: Controller-Action with custom Json return
[HttpPost]
public ActionResult Edit(SupplierQuoteDto supplierQuoteDto)
{
// ........... code
if (_userContext.EquipmentAction.ClickedAction == ActionType.Create)
return Json(new { target = "Create" });
else if (_userContext.EquipmentAction.ClickedAction == ActionType.Edit)
return Json(new { target = "Edit" });
else
return new EmptyResult();
}
3: Alternatively if you want to catch also the EmptyResult() then in the JavaScript, check simply in the
success: function (data1) {
if (data1.toString() == "") {
// .... alert
}
else {
/// .... go on with coding
}
}
check your javascript code where you do the post. You have a typo: '.' instead of ',':
$.post(url, mydata, function(data) { alert(data); }, 'json');

display validation messages using JsonResult

How can I return custom validation messages using JsonResult and AJAX?
Here is my controller action to add a student in StudentDB.
UPDATED:
[HttpPost()]
public ActionResult AddStudent(string studentName, int studentId)
{
var studentPresent = studentTable.Students.Where(s => s.StudentID == studentId&& b.StudentName == studentName);
if (studentPresent == null || !studentPresent .Any())
{
var student = new Student()
{
StudentName = studnetName,
StudentID = studentId,
};
studentTable.AddObject("Student", student);
studentTable.SaveChanges();
}
return new JsonResult();
}
Here is my JavaScript:
function addStudent() {
$.ajax({
type: 'POST',
url: '/StudentAdmin/AddStudent',
data: {
studentName: $('#studentName').val(),
studentNumber: GetTextBoxValue('#studentNumber'),
},
success: function (result) {
if ($('#studentPresent').val() == null) {
showMessage('Success', 'Student saved successfully.', '', false);
} else {
showMessage('Error', 'Student already present in database.', '', false);
}
GetGrid('#studentGrid').ajaxRequest();
hideForm();
},
studentPresent: function (result) {
showMessage('Error', 'Student Already present in Database.', '', true);
}
});
}
I want to display the "error" message if this student is already present in database.
Also, Is there a way of passing more validation messages to JasonResult?
Thanks in advance.
You can pass any object to the JsonResult object and it will be serialized (or it will attempt to serialize) down to the javascript.
return new JsonResult(new { Anything = "Hello World" });
That results in a JSON object like so:
{"Anything":"Hello World"}
Being rendered to your javascript in the result variable.
Your code above actually doesn't show any error message being generated; you would need a try / catch block if you want to get the text of the SQL exception.
EDIT:
You would have code like so:
return Json(new { message = "Success" }); // success message
return Json(new { message = "Failure" }); // fail message
And then in javascript, your callback is like so:
success: function(result)
{
if(result.message == "Success")
// Show success message
else
// Show Error Message
}
You can return Json(new {result = "Success"});

Categories

Resources