How to call and pass values to a controller method from jquery - javascript

I have a http controller which is called from a getJSON method. Its working pretty good. But now I want to do the same operation performed in handler in a controller method. I am sending a value through getJSON to handler and it perform with that value.
Here is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
and here is my handler
public void ProcessRequest(HttpContext context)
{
try
{
string strURL = HttpContext.Current.Request.Url.Host.ToLower();
//string ProfileName = context.Request.QueryString["profilename"];
string strProfileName = context.Request["ProfileName"];
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
}
catch
{
}
}
how can I call and pass 'ProfileName' to a controller method ?

Your code is correct and you should be able to retrieve the ProfileName with the following:
string strProfileName = context.Request["ProfileName"];
And if you wanted to pass it to a controller action simply define this action:
public ActionResult SomeAction(string profileName)
{
var profileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
var request = new ProfileSearchCriteria { Name = profileName };
var profileDetails = profileDataService.GetList(request);
return Json(profileDetails, JsonRequestBehavior.AllowGet);
}
and then invoke your controller action with AJAX:
<scirpt type="text/javascript">
$(document).ready(function () {
var url = '#Url.Action("SomeAction")';
$.getJSON(url, { profileName: 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
</script>

You almost have it. Here is an example:
Javascript
function someFunction(e) {
$.post("#Url.Action("MethodName", "ControllerName")", { ParameterName: e.value }, function(data) {
$("#someDiv").html = data;
});
}
C# Controller
[HttpPost]
public ActionResult MethodName(string ParameterName)
{
return "Hello " + ParameterName;
}
If you passed in your name to the JavaScript function "someFunction", the controller would return "Hello [your name]". Help?

Related

Pass a value to my controller with $.get() javascript to my controller method

Here is my goal:
I'm trying to display the details of an event in my modal.
For that, I execute a javascript script which returns to the "GetEventsDetails" method of my "Event" controller with the id of the event.
When I debug with Chrome, I see the id pass except that in my controller, the value is always 0.
I do not really understand why, I checked a lot on the net and everything seems right on my side!
Is it because I do not use an ajax call?
Thank you in advance!
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
$.get("#Url.Action("GetEventsDetails", "Events")/" + id,
function (data) {
$('.modal-body').html(data);
})
$('#myModal').show();
}
</script>
}
[Authorize]
[HttpGet]
public async Task<ActionResult> GetEventsDetails(int Zkp)
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.EventsLines { Zkp = Zkp };
var results = await client.FindAsync(toFind);
bool isEmpty = !results.Any();
if (isEmpty)
{
return View();
}
Models.EventsLines oEventViewModel = new Models.EventsLines();
oEventViewModel = results.ToList().First();
Console.WriteLine(oEventViewModel);
return PartialView(oEventViewModel);
}
<script>
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
var urlpath = "/ Events / GetEventsDetails /" + id;
$.get(urlpath, function (data) {
$('.modal-body').html(data);
});
$('#myModal').show();
}
</script>
And Your Controller
public async Task<ActionResult> GetEventsDetails(int id)

.net core Razor pages with JQuery AJAX

I am trying to call a Razor Page Handler using JQuery AJAX. Here is the sample code.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val() + "?handler=SelectByID";
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function () {
$("#msg").html("Error while making Ajax call!" + options.error.val);
};
$.ajax(options);
});
});
</script>
Razor Page cs code:
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
[BindProperty]
public FileRecord FileRecord { get; set; }
public List<SelectListItem> UserList { get; set; }
public string SelectedSectionId { get; set; }
public CreateModel(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
public async Task<IActionResult> OnGetAsync()
{
//Prepare UserList
UserList = new List<SelectListItem>();
List<ApplicationUser> Users = await _context.Users.ToListAsync();
foreach (var item in Users)
{
string role = Enum.GetName(typeof(EmRoles), EmRoles.NormalUser);
if (await _userManager.IsInRoleAsync(item, role) && item.IsEnabled)
{
UserList.Add(new SelectListItem()
{
Text = item.FullName,
Value = item.Id
});
}
}
//Sections
ViewData["Sections"] = new SelectList(_context.Sections, "Id", "Name");
//FileNOs
ViewData["Files"] = new SelectList(_context.FileRegisters, "Id", "FileNo");
//ViewData["ReceiverUserId"] = new SelectList(_context.Users, "Id", "Id");
//ViewData["SenderUserId"] = new SelectList(_context.Users, "Id", "Id");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//Two File Records have to be created. One For Sender & One for receiver.
FileRecord SenderRecord = new FileRecord
{
//create unique file id
//FileId = Guid.NewGuid().ToString(),
OutDate = DateTime.Now,
};
FileRecord ReceiverRecord = new FileRecord
{
//create unique file id
//FileId = SenderRecord.FileId,
InDate = SenderRecord.OutDate,
};
//Current logged-in user
var user = await GetCurrentUserAsync();
SenderRecord.OwnerUserId = user.Id;
//Receiver
ReceiverRecord.OwnerUserId = FileRecord.ReceiverUserId;
ReceiverRecord.SenderUserId = SenderRecord.OwnerUserId;
//Sender Record
if (await TryUpdateModelAsync<FileRecord>(SenderRecord, "FileRecord", f => f.FileId, f => f.Remarks, f => f.Gist, f => f.ReceiverUserId))
{
//Receiver Record
if (await TryUpdateModelAsync<FileRecord>(ReceiverRecord, "FileRecord", f => f.FileId, f => f.Gist))
{
_context.FileRecords.Add(SenderRecord);
_context.FileRecords.Add(ReceiverRecord);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
//If it reaches here. that means some error occurred.
return null;
}
}
The Issue is am not getting a call to Razor Page Handler defined above. If i skip the SectionId parameter passed-in & call only the handler. it is working fine. but it is not working when parameter is sent to the handler, default OnGet() is being called.
Help plz.
You don't need to append your handler parameter
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val();
You also need to decorate the method with the HttpGet attribute
[HttpGet("GetSelectByID")]
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
Then your URL to call this method needs to be
http://localhost:xxxx/FileMovement/Create/GetSelectByID?SectionId=yyy
When you have more than one GET defined on a controller you must tag the additional GET methods with the HttpGet attribute and add a string to define the name of that method.
Finally i was able to solve the issue.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "?handler=SelectByID" + "&SectionId=" + $("#SectionId").val();;
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function (data) {
$("#msg").html("Error while making Ajax call!" + data.error.val);
};
$.ajax(options);
});
});
Everything was right except i have to use "&" in "&SectionId="

how can i pass an array in window.location without ajax call

I want to send list array in ExportTo Method, but in ExportTo method student parameter get null value. If I use ajax it will work fine. But have to use window.locatoin for pass list array.
View
$(document).ready(function () {
$("#SaveBtn").click(function () {
var student = {
Name: "Tanzid",
Department: "CSE"
};
var student1 = {
Name: "Yasir",
Department: "BBA"
};
var list = [];
list.push(student);
list.push(student1);
var url = '#Url.Action("ExportTo", "Students")';
var a = JSON.stringify(list);
window.location = url + '?' + a;
});
})
.
Controller
Public void ExportTo(List<Student> student)
{
}
Iv'e tested some scenario of your problem and its work without using ajax:
Commented first your code coz i don't have it.
From Index View:
#{
ViewBag.Title = "Index";
}
<script src="~/scripts/jquery-1.10.2.js"></script>
<h2>Index</h2>
<script>
$(document).ready(function () {
var person = [];
person.push("Reign");//change like $("#idname").val();
person.push("John");
var listOfObjects = [];
person.forEach(function (names) {
var singleObj = {}
singleObj['name'] = names;
singleObj['dept'] = 'IT Dept.';
listOfObjects.push(singleObj);
});
var url = '#Url.Action("Sample", "Home")';
window.location = url + '?id=' + JSON.stringify(listOfObjects);
})
HomeController:
public ActionResult Sample()
{
string getval = Request.QueryString["id"];
string concat = #"{""data"":" + getval + "}";
ValList vl = new JavaScriptSerializer().Deserialize<ValList>(concat);
foreach (var item in vl.data)
{
Console.WriteLine("dept: {0}, name: {1}", item.dept, item.name);
}
return View();
}
public class ValList
{
public List<Values> data { get; set; }
}
public class Values
{
public string name { get; set; }
public string dept { get; set; }
}
It's all working its just depend on your project code with this:
//var List = [];
//var a = {
// Name: $("#").val(),
// Dept: $("#").val()
//};
//List.Push(a);
This is all i got..
It's Tested according to your needs.. Good Luck

Knockout.js How should I add computed value to observaleArray?

I need to add to observableArray computed values, my current code is look like this:
self.prices = ko.observableArray();
.....
var pax = $("select#ticketsnumber option:selected").val();
var irt;
if ($("input[name='isrt']").is(":checked")) {
irt = 1;
} else {
irt = 0;
}
$.each(self.prices(), function (price) {
price.FinalPrice = ko.computed(function() {
return prices.Price * irt * parseInt(pax);
});
});
But I do not have any idea how should I call binding of this computed value (currently this way - <span name="totalprice" data-bind="text: ko.utils.unwrapObservable($data.FinalPrice)">) as well as this just seemed like computed value has not been added - binding result show 0.
Data model:
public class PriceItem
{
...
public string Price { get; set; }
...
public int FinalPrice { get; set; }
}
This is the way how I retrieve data to self.prices:
self.getprices = function () {
var destinationtypefrom = $("select#optionsfrom option:selected").attr("name");
var destinationtypeto = $("select#optionsto option:selected").attr("name");
var fromcode = $("select#optionsfrom").val();
var tocode = $("select#optionsto").val();
var json = { desttypefrom: destinationtypefrom, desttypeto: destinationtypeto, codefrom: fromcode, codeto: tocode, 'DepartureDate': $("#departure").val(), 'ReturnDate': $("#return").val() };
$.ajax({
url: "/Home/GetFlights",
data: json,
type: "post",
cache: false,
success: function (result) {
if (result.Error == null) {
self.prices(result);
ko.mapping.fromJS(result, {}, self.prices);
} else {
$("#modalerror").on("show.bs.modal", function () {
var modal = $(this);
modal.find("#errormsg").text(result.Error);
});
}
},
error: function (xhr) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
The main problem is that your $.each is wrong by assuming the first argument to be the actual element in the prices array. In fact, the first argument is the index, the second argument is the actual price you want to augment.
Also, you seem to have a typo in the computed function calculation, it's price.Price instead of prices.Price.
Try this:
$.each(self.prices(), function (index, price) {
price.FinalPrice = ko.computed(function() {
return price.Price * irt * parseInt(pax);
});
});
And in your HTML, something like:
<div data-bind="foreach: prices">
<span name="totalprice" data-bind="text: FinalPrice"></span>
</div>
See Fiddle

Error in getting action parameter in MVC controller from javascript

I need to pass values from javascript to my controller action.
$.getJSON('/gallery/PublishImage', { imageid: itemsarray }, function (mydata) {
});
In javascript, it have a value. At the controller, it is null
public ActionResult PublishImage(string imageid)
{
var mydata = imageid;
return Json(mydata,JsonRequestBehavior.AllowGet);
}
how to resolve this.
my entire code is:
function publish() {
debugger;
var $trash = $("#trash li");
var itemsarray = [];
var lis = document.getElementById("trash").getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
var item = lis[i].children[0].id;
itemsarray.push(item);
}
$.getJSON('#Url.Action("PublishImage")', { imageids: itemsarray }, function (mydata) {
});
in controller
public ActionResult PublishImage(string[] imageids)
{
var mydata = imageids;
return Json(mydata,JsonRequestBehavior.AllowGet);
}
for testig used string. but in the above code also return null.
is any thing am missed?
Given the name of this javascript variable I strongly suspect that itemsarray is not a string but some kind of javascript object (an array?). It must be string for this to work:
var itemsarray = 'foo bar';
$.getJSON('/gallery/PublishImage', { imageid: itemsarray }, function (mydata) {
});
If you want to send an array then you could do that:
var itemsarray = ['foo', 'bar', 'baz'];
$.getJSON('/gallery/PublishImage', { imageids: itemsarray }, function (mydata) {
});
and your controller action:
public ActionResult PublishImage(string[] imageids)
{
var mydata = imageids;
return Json(mydata, JsonRequestBehavior.AllowGet);
}

Categories

Resources