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;
...
...
Related
I have a form that contains different fields for user to fill in and also allow user to attach image. Below is my code to send data to the controller, I can see the image in my controller but I am not sure how to access rest of form data in controller:
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var data = new FormData();
var files = $("#File").get(0).files;
if (files.length > 0) { data.append("File", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: data,
processData: false,
dataType: "html",
contentType: false
};
$.ajax(options).done(function (data) {
$('#ProdList').html(data);
});
return false;
};
$("form[data-ajax='true']").submit(ajaxFormSubmit);
});
My controller :
public ActionResult Create(PostViewProduct postProduct)
{
//code......
}
PostViewProduct model shows only image fields with data rest showing null:
Do I have to add each field using formdata.append() or is there better way to send all the data to controller and then access the data in controller.
Thanks
Try this:
var data = new FormData($(this)[0]);
instead of var data = new FormData();
Try following, this will put the data in right format if all input is within the form.
data = $form.serialize();
You basically need to send the files in FormData along with other form element data.
$(function () {
var ajaxFormSubmit = function () {
var fdata = new FormData();
$('input[name="Image"]').each(function (a, b) {
var fileInput = $('input[name="Image"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("Image", file);
}
});
// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
var frmUrl = $(this).attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: fdata,
processData: false,
contentType: false,
success: function (e) {
console.log(e);
}
});
return false;
};
$("form[data-ajax='true']").submit(ajaxFormSubmit);
});
Assuming your view model has a property called Image of type HttpPostedFileBase for accepting the posted file and your form has an input for that
public class YourViewModel
{
public HttpPostedFileBase Image { set;get;}
//Your other existing properties
}
and your form has an file input tag with name "Image".
<input type="file" name="Image" />
There is an Api method called via Ajax. After parsing and other necessary things has been finished, I get the following result.
["IG4","E1 ","E16"]
As soon as the results received, it calls another MVC ActionResult to display data from the database, where the postcode attribute of the object contains one of these Json results. However it does not work.
public ActionResult SearchResult(JsonResult postcode)
{
var posts = db.Posts.Where(p => p.PostCode.Contains(postcode));
return PartialView("postlist", posts);
}
When the ActionResult is called via Ajax, I checked what url is being called and got the following result
SearchResult?postcode%5B%5D=IG4&postcode%5B%5D=E1+&postcode%5B%5D=E16
$('#searchBtn').on('click', function () {
var _postcode = $('#searchPostcode').val();
var _distance = $('#searchDistance').val();
alert("postcode " + _postcode + " distance " + _distance);
var _url = '#Url.Action("GetPostcodesWithin", "Api/PostcodeApi")'; // don't hard code url's
$.ajax({
type: "GET",
url: _url,
data: { postcode: _postcode, distance: _distance },
success: function(data) {
alert("search ok");
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
success: function (data) {
alert("Post results called");
$("#postList").html(data).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Json data returned from GetPostcodesWithin method is displayed on the top, which is passed onto SearchResult
You first need to change the method to
public ActionResult SearchResult(IEnumerable<string> postcode)
Then change the 2nd ajax call to
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
traditional: true, // add this
success: function (data) {
....
}
})
The parameter postcode in the SearchResult() method will then contain the 3 string values from your array.
Because you now have a collection of strings, your query now needs to be
var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));
Side note: Your second value contains a space ("EF ") which may need to be trimmed?
I am using Kendo with MVC 5. I have several form inputs including a fileupload control. Onclick of a button I am building a json object with the values of the inputs and sending it through via an AJAX call.
I want to know how I can include the selected file from the file upload control in the json object that is sent. Here is the code for the upload control:
$(document).ready(function () {
$("#files").kendoUpload({
multiple: false
});
});
And then the ajax call sending the form data:
var ro = new Object();
// ...... //populate some properties
var jsonString = JSON.stringify(ro);
$.ajax({
url: '#Url.Action("Save", "Service")',
data: jsonString ,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
});
The receiving controller action look like this:
public ActionResult Save(MyViewModel model)
{
var obj = //call something here then return resulting obj
return this.Json(obj, JsonRequestBehavior.AllowGet);
}
Any help is appreciated.
Try
$("#files").kendoUpload({
multiple: false,
async: {
saveUrl: '#Url.Action("Save", "Service")',
autoUpload: true
},
upload: function (e) {
var ro = new Object();
//......//populate some properties
var jsonString = JSON.stringify(ro);
e.data = jsonString;
}
});
In your controller:
public ActionResult Save(IEnumerable<HttpPostedFileBase> files, string model)
// string because you used JSON.stringify and it is a string, do not stringify, if you need an object
{
var js = new JavaScriptSerializer();
var objetModel = js.Deserialize<MyViewModel>(model);
var obj = //call something here then return resulting obj
return Json(obj, JsonRequestBehavior.AllowGet);
}
I did not test it - it is just to get you an idea how to pass an additional information along with the uploaded binary file
function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html(reponse);
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});
I am trying to pass variable q to a php file and get back the result . I am getting the result but I am getting an error paramete q is undefined .
You can use JSON.stringify:
function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html( JSON.stringify(reponse) );
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});
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>