Url.Action Passing string array from View to Controller in MVC# - javascript

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action.Currently I can't pass my parameters. I am new in MVC3.
Pls let me know why I can't pass parameter to ActionResult..I already define ActionResult with Same parameter name..
thanks all in advance....
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
var columnNames = "";
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
});

Try this,
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
// columnNames is an object now
var columnNames = {};
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames[i] = $("#grid")[0].p.colModel[i].name;
}
}
var Val1 = jQuery(txt_search1).val();
document.location = "Home/Index/" + $.param({ Val1 = Val1 , columnNames = columnNames });
});
Your action that takes columnNames as a string array
public ActionResult Index(string val1, string[] columnNames)
{
// Your code
}
UPDATE:
If the URL becomes too big you can submit the values through form using POST method. If your view already have a form use that else create a dynamic one on the fly and submit the values through POST.
$('#export-button').click(function () {
var Val1 = jQuery(txt_search1).val();
$("#hidden-form").remove();
// create a form dynamically
var form = $('<form>')
.attr({ id: "hidden-form",
action: "/Home/Index",
method: "post",
style: "display: none;"
})
.appendTo("body");
// add the "Val1" as hidden field to the form.
$('<input>').attr({ name: "Val1 ", value: Val1, type: "hidden" }).appendTo(form);
var columnLength = $("#grid")[0].p.colNames.length;
// add the "columnNames" as hidden fields to the form
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
var t = $("#grid")[0].p.colModel[i].name;
$('<input>').attr({ name: "columnNames", value: t, type: "hidden"
}).appendTo(form);
}
};
// submit the form
form.submit();
});

for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
Hi Louis,
Your are trying to access javascript varaibles Val1 and columnNames from the server side tag and it is not possible. For more details, please refer this URL.
You can do it by following way.
var jsonData = { val1 : Val1, columnNames : columnNames };
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: "Home/Index", // Location of the service
data: jsonData,
contentType: "application/json; charset=utf-8", // content type sent to server
processdata: true, //True or False
success: function () {
alert("success")
}
});
On your controller side you have to write like
public ActionResult Index(string val1, string columnNames)
{
// Your code
}

You tagged JQuery-Ajax but i don't see any ajax attempt in the code example? So i am guessing you want to know an Ajax orientated solution. You're probably not using Zend Framework, but i hope this answers helps point you in the right direction to a solution.
From JS/Zend framework experience you could look at something like
$('#export-button').click(function () {
....
var actionUrl= "/controller/action/";
$.ajax({
url: actionUrl,
data: {
variable1: "OrgDataExport",
variable2: "Search",
Val1: Val1,
columnNames: columnNames
},
dataType: "json",
success: function(json) {
//do stuff
}
});
....
});
In the ZendFramework controller you can then grab the variables on the request:
$Val1 = $this->_request->getparam("Val1");

Related

Remove or escape double quotes

I'm trying to store items in localStorage; here is my function:
function AddToCart(varer) {
var users = JSON.parse(localStorage.getItem("users") || "[]");
users.push(varer);
console.log(varer);
localStorage.setItem("users", JSON.stringify(users));
}
And result will be in under Application Tab :
And then I'm trying Looping through localStorage and send data to controller:
var holderHTML = '';
var params = "";
var seperator = "";
var info = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < info.length; i++) {
var Val = info[i];
var key = JSON.stringify(Val)
params += seperator + "items=" + key;
seperator = "&";
}
$.ajax({
type: "GET",
url: "/User/serializeItemsLine",
data: params,
dataType: 'json',
success: function (values) {
console.log(values);
}
})
But the data I'm trying to send contains double quotes (decoded %22) and because of that my action couldn't retrieve data:
Request URL: http://localhost:xxxx/User/serializeItemsLine?items=%22ae90ac1a-64c4-49a7-b588-ae6b69a37d47%22&items=%223e58aa74-4585-4bee-b2e0-ed39a1d95442%22
Query string parameters :
items: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
items: "3e58aa74-4585-4bee-b2e0-ed39a1d95442"
Decoded results:
items: %22ae90ac1a-64c4-49a7-b588-ae6b69a37d47%22
items: %223e58aa74-4585-4bee-b2e0-ed39a1d95442%22
Action:
[HttpGet]
public string serializeItemsLine(Guid[] items) {
}
Try doing it this way: + "items=" + Val.
There is no need here to call JSON.stringify(). Your API isn't expecting JSON, so you shouldn't feed it JSON.

System.Data.Entity.DynamicProxies

I tried this code in my controller Can any one show me the solution:
public JsonResult GetMembers(Member member)
{
//var list = repository.GetAll().Select(x => new ViewModel.MemberView
//{
// Memberid = x.id,
// Name = x.name,
// EmailAddress = x.Email,
// Role = x.role.rolename,
// ReportingRoleId = Convert.ToInt32(x.reportingroleid)
//});
var list = repository.GetAll();
return Json(list , JsonRequestBehavior.AllowGet);
}
javascript function
<script type="text/javascript">
debugger;
alert('first');
google.load("visualization", "1", {packages:["orgchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Organization/GetMembers",
data :'{member:"+JSON.stringify(member)+"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Member Name"+data);
//var data = new google.visualization.DataTable();
//data.addColumn('string','name');
//data.addColumn('string', 'role');
//data.addColumn('string', 'ToolTip');
//for (var i = 0; i < r.length; i++) {
// var memberId = r[i][0];
// var Name = r[i][1];
// var role= r[i][2];
// var reportingrole= r[i][3] != null ? r[i][3].toString() : '';
// data.addRows([[{
// v: employeeId,
// f: Name + '<div>(<span>' + role + '</span>)</div><img src = "/Pictures/' + memberId + '.jpg" />'
// }, reportingrole, role]]);
//}
// var chart = new google.visualization.OrgChart($("#chart")[0]);
// chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r);
},
error: function (r) {
alert(r);
}
});
}
It was Error
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.NewProjects_A3B55EADDAEF6C59245BBD2495E29ECFE10B583596DB24AADF23A4990342D104'.
I had the same error, but this is worked for me, this is when you want to select
public MyDbContext() : base("name=MyDbContext"){this.Configuration.ProxyCreationEnabled = false;}
before you call yout table use this this.Configuration.ProxyCreationEnabled = false;
You should convert your data to list before returning it. EF return proxies for lazy loading and stuff. Try below code.
var list = repository.GetAll().ToList();
Also Look at this.
Why is EF returning a proxy class instead of the actual entity?

View is not passing the model to controller - ASP.Net MVC

This is a basic passing of values from view to controller, but this does not seek to work.When I click the update button that functions to update the record in the database, the values from view, does not correctly pass the values to controller. Upon putting debugger in the javascript, the each variables were able to correctly got its values and evn the object where they are stored.
What could possible the reason for this problem?
here's the button onclick event code in Javascript.
$('#updatePrescription').click(function () {
debugger;
ValidateFields();
var drugListIsEmpty = CheckDrugList();
var error = $(".text-danger").length;
if (error == 0 && !drugListIsEmpty) {
debugger;
var prescription = [];
var template = {};
template.templateName = $("#prescriptionTemplateName").val();
template.templateTypeId = $('input[name=templateTypeId]:checked').val();
template.prescriptionTemplateItemList = [];
template.instructionId = $('.instruction').val();
template.frequencyId = $('.frequency').val();
template.day = $('.inputDays').val();
template.quantity = $('.inputQuantity').val();
template.dispenseLocationId = $('.selectDispenseLocation').val();
template.statusId = $('.status').val();
//template.categoryId = $('.templateCategory').filter(":visible").last().val();
template.templateId = $('#prescriptionTemplateId').val();
//if (template.categoryId == null) {
// template.categoryId = 0;
//}
var x = 0;
$('#tblPrescriptionSaveTemplateBody tr').each(function (key, value) {
debugger;
var row = $(this).closest('tr');
var next_row = $(row).next();
var drugId = $(value).find('.drugId').val();
var dosage = $(value).find('.inputDosage').val();
var dosageUnitId = $(value).find('.selectUnitId').val();
var statusId = "41";
var remarks = $(value).find('.inputDescription').val();
var groupId = $(value).find('.inputGroupNo').val();
var unit = $(value).find('.selectUnitId').val();
var prescriptionTemplateItemId = $(value).find('.prescriptionTemplateItemId').val();
x++;
var obj = {
// templateId: prescriptionTemplateId,
prescriptionTemplateId: template.templateId,
prescriptionTemplateItemId: prescriptionTemplateItemId,
drugId: drugId,
dosage: dosage,
dosageUnitId: dosageUnitId,
instructionId: template.instructionId,
frequencyId: template.frequencyId,
day: template.day,
quanitity: template.quantity,
unit: unit,
remarks: remarks,
dispenseLocationId: template.dispenseLocationId,
groupId: groupId,
statusId: template.statusId
}
template.prescriptionTemplateItemList.push(obj);
//prescription.push(obj)
})
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(template),
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href = '/WestMedicinePrescriptionTemplate/Index';
}
});
}
});
This is expected to pass the result of model in parameter "newtemplate" in the controller, but it results to null
public ActionResult UpdateTemplate([FromBody] PrescriptionTemplateVM newtemplate)
{
int empId = Convert.ToInt32(HttpContext.Session.GetInt32("EmployeeId"));
var notif = "Update Failed.";
try
{
if (ModelState.IsValid)
{
bool updateSuccessful = _prescription.UpdatePrescriptionTemplateAndItems(newtemplate, empId);
if (updateSuccessful)
{
notif = "Update Successful.";
}
}
}
catch (Exception ex)
{
notif = ex.Message;
}
return Json(new { notification = notif });
}
What could be the problem in the code
do like this:
[HttpPost]
public ActionResult UpdateTemplate(PrescriptionTemplateVM newtemplate)
You need to make sure that you are using the same variables names that you defined in PrescriptionTemplateVM
and dont convert the data to Json. do like this:
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: {newtemplate: template},
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href =
'/WestMedicinePrescriptionTemplate/Index';
}
});

JS insertHtml without focus?

I have some code written in PHP with textarea input field. I also have a JS code that inserts html code into field:
$('form textarea#response').ready(function() {
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0, len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
var test = populateGet();
var ticid;
for(var key in test) {
if(Object.prototype.hasOwnProperty.call(test, key)) {
var val = test[key];
ticid = val;
}
}
$('form select#cannedResp').val('original');
var fObj = $(this).closest('form');
var $url = 'ajax.php/tickets/'+ticid+'/canned-resp/original.json';
$.ajax({
type: "GET",
url: $url,
dataType: 'json',
cache: false,
success: function(canned){
console.log('dupa');
//Canned response.
var box = $('form textarea#response'),
redactor = box.data('redactor');
if(canned.response) {
if (redactor){
redactor.insertHtml(canned.response);
}else{
box.val(box.val() + canned.response);
box.blur();
}
//if (redactor)
//redactor.observeStart();
}
//Canned attachments.
var ca = $('.attachments', fObj);
if(canned.files && ca.length) {
var fdb = ca.find('.dropzone').data('dropbox');
$.each(canned.files,function(i, j) {
fdb.addNode(j);
});
}
document.getElementById('focustest').focus();
}
})
.done(function() { })
.fail(function() { });
});
The problem is that execution of above code (redactor.insertHtml(canned.response);) causes focus on the textarea. The code is executed on page load.
Is there any way I can insert the content into field without causing the focus to placed on this field?
Thank you in advance and best regards
Tom

How to pass the select box value as an array using AJAX from one page to another in PHP?

var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.

Categories

Resources