My task is to save image into the database dynamically,whenever the user browses the img and clicks save button
I am using asp.net mvc3,razor view and mysql is my database
I am trying to pass the browsed img file to the controller and there in the controller i am converting it into byte format
and save it into the db.But when i put a braekpoint it is showing null,indicating that the file is not pasing to the controller
Could anyone please help me out in this
Below is my View and Controller
$(document).ready(function () {
$("#photos").kendoUpload();
$("#save").click(function (event) {
alert("started");
url = 'Home/Details';
var b;
$.ajax({
type: "POST",
url: '/Home/Details',
data: { b: $('#photos').load(url) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (str) {
alert("hai");
alert(str.st);
}
});
});
});
Controller:
public ActionResult Details(HttpPostedFileBase b)
{
try
{
b = Request.Files[1];
byte[] imageSize = new byte[b.ContentLength];
b.InputStream.Read(imageSize, 0, (int)b.ContentLength);
Image g = new Image();
g.Img = imageSize;
dbContext.Add(g);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
}
var str = new { st = "saved" };
return Json(str, JsonRequestBehavior.AllowGet);
}
}
Firstly I don't think you can submit file using Ajax since it is against JavaScript security model. You will need to use some other way for posting it ajax way. Here are some JQuery plugin for ajax file upload :
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/
If you want to use normal form post then you would have to set form element's encrypt property to "multipart/formdata" else the server just send file name and not the file itself.
You cannot upload files via standard AJAX
The return value of .load() is NOT the content loaded - it returns the jquery object. So you're trying to post the jquery object, NOT image data.
Related
I have a controller that returns a JsonResult
[HttpGet]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
In my view I'd like to fill a var with the data from that method. In an older MVC project I remember I'd write an ajax call to fill the var. Something like this:
var markers;
$.ajax({
type: 'POST',
url: '/Map/ShopMarkers',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
markers = result;
}
});
Or I could return a string to a view and Json.Parse it there inside a script tag.
Neither of these seem right. Is there a better way to fill my var in .Net Core?
Your client code is currently making the ajax call with POST type request. But your action method is decorated with HttpGet. So you should be getting a 404 error (If you inspect your browser dev tools, you should be able to see the status of the network (ajax) call)
[HttpPost]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
This should work assuming your code inside ShopMarkers method is not crashing ! (throwing any exceptions or so)
In your client side code you are trying to send an object. If you are sending a complex object, you should specify the contentType as "application/json" and send the data using JSON.stringify method.
var dataType = "application/json";
var data = { userId: 12, Password: 'ss' };
$.ajax({
type: 'POST',
url: '/Home/ShopMarkers',
dataType: 'json', // not really needed in your case
contentType: dataType,
data: JSON.stringify(data),
success: function (result) {
var markers = result;
console.log(result);
//Use result only here. Not outside
}
});
Since the ajax call is sending data in the request body, you should decorate the method parameter with [FromBody] attribute so that model binder will be able to map the posted data (from the request body) to your parameter.
[HttpPost]
public JsonResult ShopMarkers([FromBody] YourUserViewModel model)
{
//to do : Return some JSON
}
I am working on a web project that involves a cross-domain call, and I decided to use Knockout.js and ASP.NET Web Api. I used the Single Page Application template in VS 2012, and implemented the Knockout class as it is. The page works great when I make JSON call from the same domain, but when I try using JSONP from the remote server the knockout does not seem to bind the data. I can see the JSON data received from the remote while making JSONP call, but knockout cannot bind the data.
Here is my JavaScript ViewModel classes:
window.storyApp.storyListViewModel = (function (ko, datacontext) {
//Data
var self = this;
self.storyLists = ko.observableArray();
self.selectedStory = ko.observable();
self.error = ko.observable();
//Operations
//Load initial state from the server, convert it to Story instances, then populate self
datacontext.getStoryLists(storyLists, error); // load update stories
self.selectStory = function (s) {
selectedStory(s); $("#showStoryItem").click(); window.scrollTo(0, 0);
storyItem = s;
}
//append id to the hash for navigating to anchor tag
self.backToStory = function () {
window.location.hash = storyItem.id;
}
self.loadStories = function () {
datacontext.getStoryLists(storyLists, error); // load update stories
}
return {
storyLists: self.storyLists,
error: self.error,
selectStory: self.selectStory
};
})(ko, storyApp.datacontext);
// Initiate the Knockout bindings
ko.applyBindings(window.storyApp.storyListViewModel);
And my DataContext class as below:
window.storyApp = window.storyApp || {};
window.storyApp.datacontext = (function (ko) {
var datacontext = {
getStoryLists: getStoryLists
};
return datacontext;
function getStoryLists(storyListsObservable, errorObservable) {
return ajaxRequest("get", storyListUrl())
.done(getSucceeded)
.fail(getFailed);
function getSucceeded(data) {
var mappedStoryLists = $.map(data, function (list) { return new createStoryList(list); });
storyListsObservable(mappedStoryLists);
}
function getFailed() {
errorObservable("Error retrieving stories lists.");
}
function createStoryList(data) {
return new datacontext.StoryList(data); // TodoList is injected by model.js
}
}
// Private
function clearErrorMessage(entity) {
entity.ErrorMessage(null);
}
function ajaxRequest(type, url, data) { // Ajax helper
var options = {
dataType: "JSONP",
contentType: "application/json",
cache: false,
type: type,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
// routes
function storyListUrl(id) {
return "http://secure.regis.edu/insite_webapi/api/story/" + (id || "");
}
})(ko);
This page: http://insite.regis.edu/insite/index.html makes the cross-domain call to secure.regis.edu, and it is not working. However the same page on secure.regis.eduinsite/index.html making JSON call works just fine.
What am I doing wrong? Any help will be greatly appreciated.
Thanks for those provided help.
I manage to solve the issue by adding WebApiContrib.Formatting.Jsonp class to my WebApi project as explained in https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp, and making a slight modification to my jQuery Ajax helper class as below:
function ajaxRequest(type, url, data, callbackWrapper) { // Ajax helper
var options = {
dataType: "jsonp",
crossDomain : true,
type: type,
jsonp: "callback",
jsonpCallback: callbackWrapper,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
Everything worked as a charm.
I suggest the following:
Create a simplified example (without Knockout) that just makes the AJAX call with simple, alert-style success and error callbacks. Affirm that it is throwing an error in the cross-domain case.
Check the following link: parsererror after jQuery.ajax request with jsonp content type. If that doesn't tell you enough, search the Web (and StackOverflow) for information on jQuery JSONP parserrors and callbacks.
If you're still stuck, and you've done #1 and seen what I expect you will see, re-write this post with your simplified example, and remove any references to Knockout (in title, tags). I know Knockout, but I don't know JSONP, and the folks who know JSONP don't seem to be touching this, so I think this question is reaching the wrong audience. Changing the title and tags to emphasize the JSONP/cross-domain aspect may get you the help you need.
I currently have a JSON object on my page which gets built up as users add items to it. This is all done in JavaScript/jQuery.
When the user is done adding items, I want to POST this object to a controller action and have the action return a strongly typed view using this data.
Currently, I have the jQuery.ajax POST sending this JSON object to an Action Method which then binds this object to my strongly typed Model. Problem is, I actually want this jQuery.ajax POST to redirect as if the JSON object were in a FORM and simply being submitted.
I also can't use the jQuery.post() method, which would redirect as required, as I need to be able to set the contentType to "application/json" so my binding works correctly. Unfortunately, the jQuery.post() method doesn't allow you to set this parameter.
I've read that the jQuery.post() method basically uses the jQuery.ajax() method, so I've been battling to get the jQuery.ajax() method to redirect.
I've also read that I can set the default contentType for all jQuery.ajax() methods which would then allow me to use the jQuery.post() method but want to try avoid this if possible.
Thanks
Edit: Updated with Saedeas suggestion:
My JavaScript on the 'Index' View:
<script language="javascript" type="text/javascript">
// Initialize the Shopping Cart object
var m_ShoppingCart = {
UserId: 10,
DeliveryInstructions: "Leave at front desk",
CartItems: []
};
$(document).ready(function () {
$.extend({
postJSON: function (url, data, callback) {
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
});
function PostDataWithRedirect() {
var url = '#Url.Action("ConfirmOrder", "Store")';
$.postJSON(url, m_ShoppingCart, function () { });
}
function AddToCart(id, itemName, price, quantity) {
// Add the item to the shopping cart object
m_ShoppingCart.CartItems.push({
"Id": id,
"ItemName": itemName,
"Price": price.toFixed(2), // Issue here if you don't specify the decimal place
"Quantity": quantity
});
// Render the shopping cart object
RenderShoppingCart();
}
function RenderShoppingCart() {
$("#CartItemList").html("");
var totalAmount = 0;
$.each(m_ShoppingCart.CartItems, function (index, cartItem) {
var itemTotal = Number(cartItem.Price) * Number(cartItem.Quantity);
totalAmount += itemTotal;
$("#CartItemList").append("<li>" + cartItem.ItemName + " - $" + itemTotal.toFixed(2) + "</li>");
});
$("#TotalAmount").html("$" + totalAmount.toFixed(2));
}
</script>
And then the Controller Action 'ConfirmOrder'
[HttpPost]
public ActionResult ConfirmOrder(ShoppingCartModel model)
{
return View(model);
}
So when the PostDataWithRedirect() JavaScript method is called it must hit the ConfirmOrder Controller Action and be redirected to the ConfirmOrder View. The Shopping Cart object on my Index view is built up entirely in JavaScript and the user then clicks a 'Proceed to Checkout' button and is redirected etc.
PS: My full working example can be found in an the article [ How to POST a JSON object in MVC ], I just need to update this code so that it can do the post and redirect as explained above
In the success method, do a location.href = "TARGET LOCATION" to cause the page to go to TARGET LOCATION.
$.ajax({
url: myurl,data,
data: myData,
// processData: false, // you may need this option depending on service setup
success: function(){
location.href = "TARGET LOCATION";
},
type: "POST",
contentType: "application/json"
});
Return a view that redirects:
controller
return View("redirectionView");
view
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./";
</script>
EDIT
To accommodate data retention use tempdata.
controller
TempData["collectedUserData"] = collectedData;
return View("redirectionView");
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./Rebuilder/ActionMethod";
</script>
Controller Rebuilder
public ActionResult ActionMethod()
{
if( TempData.ContainsKey("collectedUserData") )
{
var collectedData = TempData["collectedUserData"];
}
//todo: use else clause to catch data not present
use collectedData to build new view
return View();
}
Maybe I'm not following the question, but why does the classic post, redirect, get pattern not work?
[HttpGet]
public ActionResult WhateverActionName()
{
YourViewModel yvm = new YourViewModel();
//Initalize viewmodel here
Return view(yvm);
}
[HttpPost]
public ActionResult WhateverActionName(YourViewModel yvm)
{
if (ModelState.IsValid) {
RedirectToAction("OtherAction", "OtherController")
}
return View(yvm);
}
Do you mean you want to do a post, have it bind to the viewmodel for validation purposes in one controller, and then have that controller post to another controller that verifies everything? If so, I suggest taking a look at this code to post in c# http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx.
Edit: Or you could just place the data in a tempdata object if the other controller action doesn't truly require a post.
Edit 2: Wait, is the question how to do the post with jquery? If so,
$("#YourForm").submit(function () {
$.post('#Url.Action("WhateverActionName", "YourController")';
});
});
Note: may be small syntax errors, but close to that. The #Url.Action is the important part.
Edit 3: This should finally work.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
Call it in your view as
$.postJSON('#URL.Action("Action", "Controller")', yourJson, callback)
And then redirect inside the controller.
Im creating a simple "Was this useful?" form with Yes and No objects- Using ASP.net webforms.
I need the submission to be done via ajax using jquery, to prevent a user from voting multiple times on the same page.. currently i have two methods Like_Click and Dislike_click in the C# code behind the page in question.
Can anyone give me some pointers on or a link to any suitable walkthroughs for simple ajax via jquery (I'm new to ajax!)
Ive looked at using the [WebMethod] identifier on each of the methods but do not really understand this method fully.
thanks
You are probably looking for jQuery's post function. Check out the examples. You'll want to do something along the lines of:
$('.myForm').submit(function(){ //define a handler for the submit event of the form
$.post($(this).attr('action'), {useful: true}); //send data via ajax
return false; //prevents the form from submitting via a normal web request
});
You can try something like below
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var like = $('#Like').val();
var dislike = $('#Dislike').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home.aspx/UpdateDB', //UpdateDB is declared as WebMethod
async: false,
data: "{'like':'" + like + "','dislike':'" + dislike + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#Like').val('');
$('#Dislike').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
Webmethod is shown below
[WebMethod]
public static string UpdateDB(string like, string dislike)
{
//Add your stuff
}
take a look more details here Call WebMethod from jquery in ASP.NET
I need a periodic refresh of .Net's partial view. It is working with Ajax.ActionLink, is there a similar feature for periodic refresh? Can I do it without using jQuery?
Zen, you could do it by a code like this:
function loadPartialView() {
$.ajax({
url: "#Url.Action("ActionName", "ControllerName")",
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
success: function(result) {
$('#YourDiv').html(result);
}
});
}
$(function() {
loadPartialView(); // first time
// re-call the function each 5 seconds
window.setInterval("loadPartialView()", 5000);
});
Remember your Action should return a PartialView.
I hope it helps you!
Maybe this can help you. Which version of MVC are you using? You can set a specified time interval for a helper method. This is the only way I've seen without using js.
Try this.
$(document).ready(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
setInterval(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
}, 30000); //Refreshes every 30 seconds
$.ajaxSetup({ cache: false }); //Turn off caching
});
It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.
In the controller section you can update the object and pass the object to the partial view.
public class ControllerName: Controller
{
public ActionResult ActionName()
{
.
. // code for update object
.
return PartialView("PartialViewName", updatedObject);
}
}