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
Related
I had asked my last question regarding this. I have one rfa file and a bigger JSon file as input. When I debug, it looks perfectly passing all values until last line:
WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
Looks like workItemSpec has some problem. Please have a look at these code fractions and please let me know what is wrong here.
code fraction from ForgeDesignAutomation.js as below:
{
var inputFileField = document.getElementById('inputFile');
if (inputFileField.files.length === 0) { alert('Please select an input file'); return; }
if ($('#activity').val() === null) { alert('Please select an activity'); return };
var file = inputFileField.files[0];
var inputFileField2 = document.getElementById('inputJsonFile');
if (inputFileField2.files.length === 0) { alert('Please select an input file'); return; }
var file2 = inputFileField2.files[0];
let activityId = $('#activity').val();
if (activityId == null)
{
alert('Please select an activity'); return
};
if (activityId.toLowerCase() === "_da4ractivity+dev")
{
startConnection(function () {
var formData = new FormData();
formData.append('inputFile', file);
formData.append('inputJsonFile', file2);
formData.append('data', JSON.stringify({
activityName: $('#activity').val(),
browerConnectionId: connectionId
}));
writeLog('Uploading input file...');
$.ajax({
url: 'api/forge/designautomation/workitems',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (res)
{
writeLog('Workitem started: ' + res.workItemId);
}
});
});
}
}```
code fraction from "CreateActivity" in DesignAutomationController.cs
``` Parameters = new Dictionary<string, Parameter>()
{
{ "inputFile", new Parameter() { Description = "input file", LocalName = "$(inputFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "inputJsonFile", new Parameter() { Description = "input Json file", LocalName = "$(inputJsonFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "outputFile", new Parameter() { Description = "output file", LocalName = "outputFile." + engineAttributes.extension, Ondemand = false, Required = true, Verb = Verb.Put, Zip = false } }
}```
code fraction from "StartWorkitem" in DesignAutomationController.cs
``` [HttpPost]
[Route("api/forge/designautomation/workitems")]
public async Task<IActionResult> StartWorkitem([FromForm]StartWorkitemInput input)
{
// basic input validation
JObject workItemData = JObject.Parse(input.data);
string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value<string>());
string browerConnectionId = workItemData["browerConnectionId"].Value<string>();
// save the file on the server
var fileSavePath0 = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName));
using (var stream0 = new FileStream(fileSavePath0, FileMode.Create)) await input.inputFile.CopyToAsync(stream0);
var fileSavePath1 = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputJsonFile.FileName));
using (var stream1 = new FileStream(fileSavePath1, FileMode.Create)) await input.inputJsonFile.CopyToAsync(stream1);
//---------------------------------------------------------------------------------------------------------------------
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// upload file to OSS Bucket
// 1. ensure bucket existis
string bucketKey = NickName.ToLower() + "-designautomation";
BucketsApi buckets = new BucketsApi();
buckets.Configuration.AccessToken = oauth.access_token;
try
{
PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
await buckets.CreateBucketAsync(bucketPayload, "US");
}
catch { };
// in case bucket already exists
// 2. upload inputFile
string inputFileNameOSS0 = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
string inputFileNameOSS1 = string.Format("{0}_inputJson_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputJsonFile.FileName)); // avoid overriding
//string inputFileNameOSS = Path.GetFileName(input.inputFile.FileName); // avoid overriding
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
using (StreamReader streamReader = new StreamReader(fileSavePath0))
await objects.UploadObjectAsync(bucketKey, inputFileNameOSS0, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
System.IO.File.Delete(fileSavePath0);// delete server copy
// prepare workitem arguments
// 1. input file
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS0),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
using (StreamReader streamReader1 = new StreamReader(fileSavePath1))
await objects.UploadObjectAsync(bucketKey, inputFileNameOSS1, (int)streamReader1.BaseStream.Length, streamReader1.BaseStream, "application/octet-stream");
System.IO.File.Delete(fileSavePath1);// delete server copy
// 1. input Json file
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS1),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 3. output file
string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "inputFile", inputFileArgument },
{ "inputJsonFile", inputJsonArgument },
{ "outputFile", outputFileArgument },
{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
return Ok(new { WorkItemId = workItemStatus.Id });
}```
```/// <summary>
/// Input for StartWorkitem
/// </summary>
public class StartWorkitemInput[![enter image description here][1]][1]
{
public IFormFile inputFile { get; set; }
public IFormFile inputJsonFile { get; set; }
public string data { get; set; }
} ```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/GktUC.png
I noticed your activity defines the "localName" of "inputFile"/"inputJsonFile" to be "$(inputFile)"/"$(inputJsonFile)"
Parameters = new Dictionary<string, Parameter>()
{
{ "inputFile", new Parameter() { Description = "input file", LocalName = "$(inputFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "inputJsonFile", new Parameter() { Description = "input Json file", LocalName = "$(inputJsonFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } }
}
This could cause some issue when resolving the naming of inputs during the job process. I would suggest you provide a concrete filename as WorkItem argument's localname and try again. For example:
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS1),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
},
// Note: if your appbunldes(addin) uses this json, this is the name your addin should know
LocalName = "inputJson.json"
};
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.
I want to send one pre request to my server before send every request. From that pre request I will receive the token from my server and than I have to add that token into all the request. This is the process.
I have try with some methods to achieve this. But I am facing one problem. That is, When I try to send pre request, it is processing with the current request. That mean both request going parallel.
I want to send pre request first and parse the response. After parsing the pre request response only I want to send that another request. But first request not waiting for the pre request response. Please let me any way to send pre request before all the request.
This is my code:
ViewModel:
`public class ListExampleViewModel
{
SecurityToken sToken = null;
public ListExampleViewModel()
{
GlobalConstants.isGetToken = true;
var listResults = REQ_RESP.postAndGetResponse((new ListService().GetList("xx","xxx")));
listResults.Subscribe(x =>
{
Console.WriteLine("\n\n..................................2");
Console.WriteLine("Received Response==>" + x);
});
}
}`
Constant Class for Request and Response:
`public class REQ_RESP
{
private static string receivedAction = "";
private static string receivedPostDate = "";
public static IObservable<string> postAndGetResponse(String postData)
{
if (GlobalConstants.isGetToken)
{
//Pre Request for every reusest
receivedPostDate = postData;
GlobalConstants.isGetToken = false;
getServerTokenMethod();
postData = receivedPostDate;
}
HttpWebRequest serviceRequest =
(HttpWebRequest)WebRequest.Create(new Uri(Constants.SERVICE_URI));
var fetchRequestStream =
Observable.FromAsyncPattern<Stream>(serviceRequest.BeginGetRequestStream,
serviceRequest.EndGetRequestStream);
var fetchResponse =
Observable.FromAsyncPattern<WebResponse>(serviceRequest.BeginGetResponse,
serviceRequest.EndGetResponse);
Func<Stream, IObservable<HttpWebResponse>> postDataAndFetchResponse = st =>
{
using (var writer = new StreamWriter(st) as StreamWriter)
{
writer.Write(postData);
writer.Close();
}
return fetchResponse().Select(rp => (HttpWebResponse)rp);
};
Func<HttpWebResponse, IObservable<string>> fetchResult = rp =>
{
if (rp.StatusCode == HttpStatusCode.OK)
{
using (var reader = new StreamReader(rp.GetResponseStream()))
{
string result = reader.ReadToEnd();
reader.Close();
rp.GetResponseStream().Close();
XDocument xdoc = XDocument.Parse(result);
Console.WriteLine(xdoc);
return Observable.Return<string>(result);
}
}
else
{
var msg = "HttpStatusCode == " + rp.StatusCode.ToString();
var ex = new System.Net.WebException(msg,
WebExceptionStatus.ReceiveFailure);
return Observable.Throw<string>(ex);
}
};
return
from st in fetchRequestStream()
from rp in postDataAndFetchResponse(st)
from str in fetchResult(rp)
select str;
}
public static void getServerTokenMethod()
{
SecurityToken token = new SecurityToken();
var getTokenResults = REQ_RESP.postAndGetResponse((new ServerToken().GetServerToken()));
getTokenResults.Subscribe(x =>
{
ServerToken serverToken = new ServerToken();
ServiceModel sm = new ServiceModel();
//Parsing Response
serverToken = extract(x, sm);
if (!(string.IsNullOrEmpty(sm.NetErrorCode)))
{
MessageBox.Show("Show Error Message");
}
else
{
Console.WriteLine("\n\n..................................1");
Console.WriteLine("\n\nserverToken.token==>" + serverToken.token);
Console.WriteLine("\n\nserverToken.pk==>" + serverToken.pk);
}
},
ex =>
{
MessageBox.Show("Exception = " + ex.Message);
},
() =>
{
Console.WriteLine("End of Process.. Releaseing all Resources used.");
});
}
}`
Here's couple options:
You could replace the Reactive Extensions model with a simpler async/await -model for the web requests using HttpClient (you also need Microsoft.Bcl.Async in WP7). With HttpClient your code would end up looking like this:
Request and Response:
public static async Task<string> postAndGetResponse(String postData)
{
if (GlobalConstants.isGetToken)
{
//Pre Request for every reusest
await getServerTokenMethod();
}
var client = new HttpClient();
var postMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(Constants.SERVICE_URI));
var postResult = await client.SendAsync(postMessage);
var stringResult = await postResult.Content.ReadAsStringAsync();
return stringResult;
}
Viewmodel:
public class ListExampleViewModel
{
SecurityToken sToken = null;
public ListExampleViewModel()
{
GetData();
}
public async void GetData()
{
GlobalConstants.isGetToken = true;
var listResults = await REQ_RESP.postAndGetResponse("postData");
}
}
Another option is, if you want to continue using Reactive Extensions, to look at RX's Concat-method. With it you could chain the token request and the actual web request: https://stackoverflow.com/a/6754558/66988
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>
my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}