I have a jquery function like this.
var jsonArg = new Object();
$(".x").each(function () {
var val1 = "Domain:" + $(this).children(".y").html();
var val2 = "shop:" + $(this).children(".z").html();
jsonArg[val1] = val2;
});
$.ajax({
type: "POST",
url: "/Home/Mappings",
data: { "jsonArg": jsonArg }
})
Now I want to send value of jsonArg to my controller.
My Controller looks like this,
[HttpPost]
public ActionResult Mappings(string Json)
{
return null;
}
I am getting null value in the controller.Please help.
Change variable Name.
[HttpPost]
public ActionResult Mappings(string jsonArg)
{
return null;
}
And Try JSON.stringify();
data: { "jsonArg": JSON.stringify(jsonArg) }
Related
I am learning ASP.net MVC - 5 and I am stuck at one problem. So I need to open a URL after successful Ajax Post Request. But I also want to pass one value to the new URL's Controller Action. Below is what I have till now.
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
},
error: function (error) {
}
});
Controller Action
[AuthorizeSettings]
public ActionResult Customize()
{
//I want to be able to access TEMPVAR value here
// code removed for brevity
return View(configData);
}
Question: How to pass the TEMPVAR data to the Customize Action
Points:
I know there are some ways to pass data. TempData,Viewbag,SessionVariable, Embedding the TEMP value in URL Request, Anonymous Objects, ViewData, Static variable for the class, Global Variable, JSON. But I am totally confused how to pass data. I am newbiew please guide me here.
EDIT:
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
TEMPDATA["value"] = TEMPVAR;
},
error: function (error) {
}
});
Based on comments, you want to send data from SaveStyles to Customize. If so, you can use TempData -
public class PersistController : Controller
{
[HttpPost]
public ActionResult SaveStyles()
{
TempData["Status"] = true;
TempData["Val"] = 4;
return Json(true);
}
}
public class SettingsController : Controller
{
public ActionResult Customize()
{
bool status = Convert.ToBoolean(TempData["Status"]);
int val = Convert.ToInt32(TempData["Val"]);
return View();
}
}
i have this return come from here
public string Get(int id)
{
return "{\"longPachage\":{\"Id\":0}}";
}
and i Receive this return by ajax with this code
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
alert(data);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
what i can to deserialize json object and print the Id value only ?
You can use this code. It may be help to you.
You are not parse the data to get JSON in string format. So you can now use this code to get JSON data in string format.
var obj = JSON.parse(data);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var obj = JSON.parse(data);
alert(obj.Id);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
yes, Stephen is right.
you have to send a json result from controller.
for exa.
public JsonResult Get(int id)
{
return Json(new
{
longPachage = new { ID = 0 }
}, JsonRequestBehavior.AllowGet);
}
and in your ajax success, just retrieve that object or dataID.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var dataID = data.longPachage.Id;
// Do with Your ID.
},
error: function (data) {
//Do anything for error here.
}
})
Change your method like this:
public ActionResult Get(int? id)
{
return Content("{\"longPachage\":{\"Id\":0}}");
}
And then in your jQuery:
$.getJSON("http://localhost:3148/api/values", {id:5}, function(data) {
var id = data.longPachage.Id;
alert(id)
});
Try to use JsonResult in MVC to return Json instead of building a string. JsonResult is just an abstact class of ActionResult. Modify your code in the controller as follows
Method 1:
public JsonResult GetTest(int id)
{
return this.Json(new { ID = 0 }, JsonRequestBehavior.AllowGet);
}
OR
Method 2:
Try to create a model class as LongPachage
public class LongPachage()
{
public int ID {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
LongPachage model = new LongPachage();
model.ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
OR
Method 3
Create Model class say TestModel and try to add LongPachage class as propery of this class.
public class TestModel()
{
public LongPachage LongPachage {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
TestModel model = new TestModel();
model.LongPachage .ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
and then in the view using AJAX GET wrapper try to implement as follows
$.get('#Url.Action("Get","ControllerName")', { id: "5" })
.done(function (data) {
// If you are using Method 1 or Method 2 alert will be as follows
alert(data.ID);
// If you are using method 3
alert(data.LongPachage.ID)
});
I have the following JQuery method for posting data to a action in my MVC contorller:
$('#btnAddNewTest').on("click", function () {
var date = $('#HIVTestTestDate').val();
var result = $('#HIVTestTestResult').val();
var cd4 = $('#HIVTestCD4Count').val();
var pID = $('#PatientID').val();
var dataToSend = { patientID: pID, testDate: date, resultID: result, cd4Count: cd4 };
$.post("/HIVInformation/AddHIVTest/", dataToSend, function (receivedData) {
location.reload(false); //Don't want to do this
});
return false;
});
Here is the Action method in my controller:
[HttpPost]
public ActionResult AddHIVTest(Guid patientID, DateTime testDate, Guid resultID, int cd4Count)
{
MvcPatientDetailsHIVViewModel model = new MvcPatientDetailsHIVViewModel(patientID);
model.LoadAllData();
try
{
//add the HIV Test
model.HIVTestResult = new Common.Models.PatientHIVTestModel()
{
ID = Guid.NewGuid(),
PatientID = patientID,
TestDate = testDate,
HIVTestResultID = resultID,
CD4Count = cd4Count
};
//call the add method
model.AddHIVTestResults();
}
catch (Exception ex)
{
ModelState.AddModelError("", ex);
}
return View("Details", model);
}
If I comment out the 'location.reload(false);' my page does not get refreshed. How do I serialize my Mvc view to be returned in the function (receivedData) delegate of the post? How do I display my view then from within the JQuery code?
if i may, i would suggest to you to use ajax, partial views, and a container div for example to load the result in it.
Example:
Script:
$(document).ready(function () {
$("#btnAddNewTest").on("click", function () {
$.ajax({
url: '#Url.Action("YourAction", "YourController")',
type: 'post',
data: {
yourData1: value1,
yourData2: value2,
},
success: function (result) {
$('#dynamicContent').html(result);
}
});
});
});
Controller:
public ActionResult YourAction(int yourData1= 1, int yourData2 = 0)
{
return PartialView("~/yourviewPath/_YourPartialView.cshtml", yourResultModel)
}
Html:
<div id="dynamicContent" class="Float_Clear">
#Html.Partial("~/yourviewPath/_YourPartialView.cshtml", Model)
</div>
Live example that I created using the same concept here
[HttpPost]
public JsonResult DelayReminder(string reminderId)
{
ReminderStatus rs = new ReminderStatus();
rs.BaseProps.RequesterUserInfo.UserID = SessionManager.Current.CurrentUser.UserID;
ReminderServiceHelper.InsertNewStatus(Convert.ToInt32(reminderId), rs);
return Json(apptype, JsonRequestBehavior.AllowGet); // Problem...
}
Instead of return Json(apptype, JsonRequestBehavior.AllowGet); how can i write below ?
return RedirectToAction("GetLawDetail", "Law", new { _lawID = baseappid });
If anybody wants to see Javascript:
$.ajax({
type: 'POST',
url: '/Reminders/DelayReminder/',
data: {
'apptype': '#ViewData["apptype"]',
'baseappid': '#ViewData["baseappid"]',
'reminderId': $("#reminderId").val(),
'ddlDelayDuration': $("#ddlDelayDuration").val()
},
dataType: 'json',
success: function (result) {
if (result != null) {
}
....
..
How can i return to Law controller to GetLawDetail actionresult inside of jsonresult ?
You can just return this action:
return GetLawDetail(baseappid)
You should also change the return type to Action result as pointed by #im1dermike.
Here's the complete code:
[HttpPost]
public ActionResult DelayReminder(string reminderId)
{
ReminderStatus rs = new ReminderStatus();
rs.BaseProps.RequesterUserInfo.UserID = SessionManager.Current.CurrentUser.UserID;
ReminderServiceHelper.InsertNewStatus(Convert.ToInt32(reminderId), rs);
return GetLawDetail(apptype); // Problem...
}
Although, it will return you the whole rendered page.
I have AJAX working for a single page, but I want it to work across all pages. How can I accomplish it?
Here is the JavaScript in scripts.cshtml:
function changeTab(tabId) {
var url = "Home/changeTab/" + tabId;
$.ajax({
url: "Home/changeTab/" + tabId,
success: function (tab) {
var t = tab;
$("#menu1").html(t);
}
});
}
I have a component Home.cs:
namespace Web.Controllers
{
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
[AcceptVerbs("GET")]
public JsonResult changeTab(int id)
{
var saveTab = id;
string username = User.Identity.Name;
[...]
return Json(username, JsonRequestBehavior.AllowGet);
}
}
}
The code works well on the Home page, but not on any other. Where do I place the changeTab function so that every page can call it?
try change your script into the following :
function changeTab(tabId) {
var url = '#Url.Action("changeTab", "Home")/' + tabId;
$.ajax({
url: url,
success: function (tab) {
var t = tab;
$("#menu1").html(t);
}
});
}