How to pass values to controler Action from Ajax Method? - ajax

Hi all i have ajax where i have some data And a controller action method ...i need to send the data to the controller action method ...when i am doing this it has null values in my controller method ,can any one correct me where am i doing worng...
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
var data = '{"AssignTo":"' + selecteditem1 + '","Status":"' + selecteditem6 + '"}';
alert(data);
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: data,
success: function () {
}
});
}
</script>
my contoller action method
[HttpPost]
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
{
if (Session["CaptureData"] == null)
{
}
else
{
model = (BugModel)Session["CaptureData"];
}
ViewBag.AssignTo = new SelectList(GetEmployee(), "EmployeeID", "EmployeeName");
ViewBag.Status = new SelectList(GetFromStatus(), "FromStatusId", "FromStatus");
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("sp_history", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.Parameters.Add("#Title", SqlDbType.VarChar).Value = model.Title;
cmd.Parameters.Add("#FixedById", SqlDbType.VarChar).Value = model.LoginName;
cmd.Parameters.Add("#AssignedId", SqlDbType.Int).Value = model.AssignTo;
cmd.Parameters.Add("#Resolution", SqlDbType.VarChar).Value = model.Resolution;
cmd.Parameters.Add("#FromStatus", SqlDbType.VarChar).Value =model.Status;
string fileName = string.Empty;
string StrFilePath = string.Empty;
foreach (BugAttachment objList in model.ListFile)
{
if (string.IsNullOrEmpty(StrFilePath))
{
fileName = objList.AttachmentName;
StrFilePath = objList.AttachmentUrl;
}
else
{
fileName = fileName + "," + objList.AttachmentName;
StrFilePath = StrFilePath + "," + objList.AttachmentUrl;
}
}
cmd.Parameters.Add("#AttachmentName", SqlDbType.VarChar).Value = fileName;
cmd.Parameters.Add("#BugAttachmentUrl", SqlDbType.VarChar).Value = StrFilePath;
cmd.Parameters.Add("#AttachedBy", SqlDbType.VarChar).Value = model.LoginName;
cmd.ExecuteNonQuery();
conn.Close();
}
return View("Edit");
}

Instead of
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
give this a try:
public ActionResult Update(BugModel model, FormCollection form, string AssignTo, string Status)
You need to use the names of the property you have used in the object your sending back as you have named them AssignTo and Status. Hope this helps.
Edit:
Try sending the object like this:
var data ={};
data.AssignTo = selectedvalue1;
data.Status = selectedvalue6;
See if that makes any difference. If your still having issues can you inspect the request in firebug/developer tools?

Try this:
var data = { AssignTo: selecteditem1, Status: selecteditem6 };
also, as per Henry's answer, use the signature:
public ActionResult Update(BugModel model,
FormCollection form,
string AssignTo,
string Status)
tho, you should of course be able to get both the required values from the form[] collection, given that you are doing an HttpPost behind the scenes:
(i.e. var assignTo = form["AssignTo"]; etc).
[Edit] - out of curiousity, can I ask why you mix and match jquery syntax with more traditional javascript object syntax. one example being where you get the value of the EmployeeID option?? why not just use var selecteditem1 = $('#EmployeeID').val();.
I also notice the ViewBag object getting updated in your HttpPost action. Are you expecting to be able to use that on returning to the view -surely not (not in terms of the ajax request anyway). A quick explanation for my curiousity would be great. In my opinion, you are trying to do too much with this action (sure, keep it DRY - but) and I'm fearful that you'll end up getting into a corner with the number of different entry points you appear to be building up. I'd suggest a gentle rewind, just to keep things a little more focussed and each action having a single responsibility.

I ended up doing the following:
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
// var data = '{AssignTo:' + selecteditem1 + '}';
// alert(data);
var AssignTo;
var Title;
Title=$("#Title").val();
var FixedBy;
FixedBy = $("#LoginName").val();
var Resolution;
Resolution = $("#Resolution").val();
var Status;
Status = $("#FromStatusId").val();
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: {AssignTo:selecteditem1,Title:Title,FixedBy:FixedBy,Resolution:Resolution,Status:Status},
success: function () {
}
});
}
</script>

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

i cant export my list to csv using mvc c#

I have been dealing with a problem for hours,kindly help me,the following is my ajax which post data to controller :
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("CreateCSVFile ","Turbine ")",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(data),
success: function(result) {}
})
It posts the result I want to controller,but problem starts from here that in my controller after making the export file,i don't see any thing in the browser to save it,i have no idea where is going wrong,the following is my controller:
public FileContentResult CreateCSVFile(string turbinename, string frm_date, string to_date)
{
var eventResult = (from c in DB.Events
where (c.m_turbine_id == turbineid.turbineID) && (c.m_time_stamp >= frmDate && c.m_time_stamp <= toDate)
select new EventLogPartialViewModel
{
Timestamp = c.m_time_stamp,
Description = c.m_event_log_description,
WindSpeed = c.m_wind_speed,
RPM = c.m_rpm,
Power = c.m_power
}).ToList().Select(x => new
{
Timestamp = x.Timestamp.ToString("dd/MM/yyyy H:mm:ss"),
Description = x.Description,
WindSpeed = x.WindSpeed,
RPM = x.RPM,
Power = x.Power
}).ToList().OrderByDescending(m => m.Timestamp);
var st = DataTag.NoExclusion;
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = ASCIIEncoding.ASCII.GetBytes(CSVExport.GetCsv(eventResult.ToList(), st));
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
}
To fit your particular function, you can do :
public FileContentResult CreateCSVFile()
{
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = Encoding.UTF8.GetBytes(csv); // or get your bytes the way you want
string contentType = "text/csv";
var result = new FileContentResult(csvBytes, contentType);
return result;
}
This is how you can create a FileContentResult.
However, I prefer to use this to send a response with a file :
[HttpGet]
public HttpResponseMessage GetYourFile()
{
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = Encoding.UTF8.GetBytes(csv); // or get your bytes the way you want
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(csvBytes);
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "YourFileName.csv"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("text/csv");
return result;
}
(adapted from How to return a file (FileContentResult) in ASP.NET WebAPI).
Extracting the "csv" part in bytes is another problem completely, I hope your problem was about the "create a file" part.

Unable to extract the string i want from the ajax post

In my asp mvc project i've got an ajax call that posts the value of a dropdown list and i want the session to be set with this value.
$('#dropDownMenu').on('click', 'li', function () {
var txt = $('#schoolButtons').text();
data = {session: txt};
var requestValue = JSON.stringify(data);
$.ajax({
url: '#Url.Action("SetSession")',
type: 'POST',
data: "requestValue="+requestValue ,
}).success(function (data, textStatus, jqXHR) {
});
});
public ActionResult SetSession(string requestValue)
{
var sessionVal = Convert.ToString(requestValue);
if (sessionVal==null)
{
Debug.WriteLine("session is null");
}
Session["key"] = sessionVal;
return Json(requestValue);
}
When I output the value of the session i'm getting the string {"session":"State School"} when all i want is "State School". I know in the function data is set to {session: txt} but how do i just extract that txt?
Regards,
Mike.
To read the JSON value you need to read it this way
var requestValue = data.session
Since you pass it as a string into the function and want to read it in the function, this is what I sugggest you do. You need to convert the string to JSON and extract the value.
public ActionResult SetSession(string requestValue)
{
var JSONData = JSON.parse(requestValue);
var sessionVal = JSONData.session;
...
...

HttpPost with AJAX call help needed

what else do i need in my code please, I have this so far:
<script type="text/javascript">
function PostNewsComment(newsId) {
$.ajax({
url: "<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").val(), success: function (data) {
$("#news-comment-content").html(data + $("#news-comment-content").html());
type: 'POST'
}
});
}
$("#textareaforreply").val("");
</script>
and
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(int newsId, string newsComment)
{
if (!String.IsNullOrWhiteSpace(newsComment))
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(newsId, newsComment, currentUser.UserId);
Zinc.DataModels.News.NewsCommentsDataModel model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return null;
}
<div class="actions-right">
<%: Html.Resource(Resources.Global.Button.Reply) %>
</div>
i have no idea how this works, because it is not working in FF???
and the other thing is i must not pass return null i must pass JSON false ???
any help please?
thanks
You should encode your request parameters. Right now you have concatenated them to the request with a strong concatenation which is a wrong approach. There's a property called data that allows you to pass parameters to an AJAX request and leave the proper url encoding to the framework:
function PostNewsComment(newsId) {
$.ajax({
url: '<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>',
type: 'POST',
data: {
newsId: newsId,
newsComment: $('#textareaforreply').val()
},
success: function (data) {
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
});
}
Also you haven't shown where and how you are calling this PostNewsComment function but if this happens on the click of a link or submit button make sure that you have canceled the default action by returning false, just like that:
$('#someLink').click(function() {
PostNewsComment('123');
return false;
});
and the other thing is i must not pass return null i must pass JSON false ???
You could have your controller action return a JsonResult in this case:
return Json(new { success = false });
and then inside your success callback you could test for this condition:
success: function (data) {
if (!data.success) {
// the server returned a Json result indicating a failure
alert('Oops something bad happened on the server');
} else {
// the server returned the view => we can go ahead and update our DOM
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
}
Another thing you should probably be aware of is the presence of dangerous characters such as < or > in the comment text. To allow those characters I would recommend you build a view model and decorate the corresponding property with the [AllowHtml] attribute:
public class NewsViewModel
{
public int NewsId { get; set; }
[AllowHtml]
[Required]
public string NewsComment { get; set; }
}
Now your controller action will obviously take the view model as argument:
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(NewsViewModel viewModel)
{
if (!ModelState.IsValid)
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(viewModel.NewsId, viewModel.NewsComment, currentUser.UserId);
var model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return Json(new { success = false });
}

cannot retrieve data in Jquery after makin $.ajax call using Jsonp

I've a function used to retrieve the data from my RESTFUL WCF Service. the returned data has to be JSON.
on the Client end I have a javascript function called autosuggest like below:
function autosuggest(location){
var uri= 'http://localhost:2043/Suggest.svc/GetAirportsjson?location='+location;
$.ajax({
url:uri,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback(e)',
success: function(e){
alert("success");
}
}); };
the Service interface as:
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetAirportsXML?location={location}")]
[OperationContract]
List<Suggestions> GetAirportDataXml(string location);
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetAirportsJSON?location={location}")]
[OperationContract]
List<Suggestions> GetAirportDataJson(string location);
And The response observed in Firebug for location=m is
[{"AirportCode":"MMZ","AirportName":"Maimana","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"MZR","AirportName":"Mazar-i-sharif","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"IMZ","AirportName":"Nimroz","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"TMR","AirportName":"Aguemar","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"BMW","AirportName":"Bordj Badji Mokhtar","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"IAM","AirportName":"In Amenas","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MUW","AirportName":"Mascara-Ghriss","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MZW","AirportName":"Mechria","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MQV","AirportName":"Mostaganem","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"HME","AirportName":"Oued Irara Apt","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"TMX","AirportName":"Timimoun","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"TLM","AirportName":"Zenata","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"}]
And I'll also Provide my service code which is
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
namespace AutosuggestAPI.svc
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Suggest : IService1
{
public string GetDateTime()
{
return DateTime.Now.ToString();
}
private static List<Suggestions> GetDistinct(List<Suggestions> suggestions)
{
var length = suggestions.Count;
var Arr = new Suggestions[length];
suggestions.CopyTo(Arr);
var dist = new HashSet<string>();
foreach (var suggestion in Arr)
{
if (!dist.Contains(suggestion.AirportCode.ToString()))
dist.Add(suggestion.AirportCode.ToString());
else
{
suggestions.Remove(suggestion);
}
}
return suggestions;
}
public List<Suggestions> GetAirportDataXml(string location)
{
var suggestions = new List<Suggestions>();
var val = string.Empty;
for (int i = 0; i < 2; i++)
{
val = i == 0 ? "AirPortName" : "AirPortCode";
SqlConnection conn = null;
try
{
// create and open a connection object
conn = new SqlConnection("Server=(local);DataBase=DBAirPortCodes;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
var cmd = new SqlCommand("sp_CheckCondition", conn) { CommandType = CommandType.StoredProcedure };
// 2. set the command object so it knows
// to execute a stored procedure
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#lookup", val));
cmd.Parameters.Add(new SqlParameter("#searchfor", location));
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var suggestion = new Suggestions()
{
_airportCode = Convert.ToString(reader["AirPortCode"]).Trim(),
_airportName = Convert.ToString(reader["AirPortName"]).Trim(),
_areaCode = Convert.ToString(reader["AreaCode"]).Trim(),
_countryCode = Convert.ToString(reader["CountryCode"]).Trim(),
_countryName = Convert.ToString(reader["CountryName"]).Trim()
};
suggestions.Add(suggestion);
}
}
finally
{
if (conn != null)
conn.Close();
}
}
var distinctList = GetDistinct(suggestions);
return distinctList;
}
List<Suggestions> GetAirportDataJson(string location)
{
List<Suggestions> suggestions = GetAirportDataXml(location);
return suggestions;
}
public List<Suggestions> GetAirportDataJsonp(string location)
{
return GetAirportDataXml(location);
}
public List<Suggestions> GetAllSuggestions()
{
var suggestions = new List<Suggestions>();
var val = string.Empty;
for (int i = 0; i < 2; i++)
{
val = i == 0 ? "AirPortName" : "AirPortCode";
SqlConnection conn = null;
try
{
// create and open a connection object
conn = new SqlConnection("Server=(local);DataBase=DBAirPortCodes;Integrated Security=SSPI");
conn.Open();
var cmd = new SqlCommand("sp_GetAllAirports", conn) { CommandType = CommandType.StoredProcedure };
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var suggestion = new Suggestions()
{
_airportCode = Convert.ToString(reader["AirPortCode"]).Trim(),
_airportName = Convert.ToString(reader["AirPortName"]).Trim(),
_areaCode = Convert.ToString(reader["AreaCode"]).Trim(),
_countryCode = Convert.ToString(reader["CountryCode"]).Trim(),
_countryName = Convert.ToString(reader["CountryName"]).Trim()
};
suggestions.Add(suggestion);
}
}
finally
{
if (conn != null)
conn.Close();
}
}
var distinctList = GetDistinct(suggestions);
return distinctList;
}
}
}
The Problem is that the call is successful and I get the Data in Browser but I cannot catch it in Jquery or Javascript.
Can someone help?
You are passing wrong string to jsonCallback.
should be
function autosuggest(location){
var uri= 'http://localhost:2043/Suggest.svc/GetAirportsjson?location='+location;
$.ajax({
url:uri,
dataType: 'jsonp',
jsonpCallback: 'jsonpCallback',
success: function(e){
alert("success");
}
});
};
Also why you are overriding default callback parameter name with default value ?
EDITED: Seems you don't really understand how jquery handles jsonp stuff.
jquery create a function to handle return of jsonp request which returns json as plain text wrapped into this function call. you can provide no function at all, and that is preferable for jquery and more straitforward
take a look at the following example
Only parameters you need to provide is datatype of jsonp
var r = $.ajax({
url : uri
, dataType:'jsonp'
, success: function (e) {
viewModel.tweets(e.results);
}});
EDITED 2: Your service should handle 'callback' parameter, and if provided, wrap up response json in the function call provided
ie
Request: http://......../GetAirportsjson?location=....&callback=mycallback
Response: mycallback({ .... you real json response goes here .... })
Until you have this you are not doing proper jsonp response

Resources