I am trying to pass the object myclass to the view page, the issue I am facing is null object is being returned back to the controller. Any pointers ?
Below is the code in my ascx page
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<myclass>" %>
<div class="upModel" style="display:none">
<%= Model%>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#load").click(function () {
try {
$.ajax({
type: "POST",
url: "Loadmyaction",
data: $("#upModel").serialize(),
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function(result) { alert("Error" + result); }
});
}
catch (err) {
alert(err.description);
}
});
</script>
**On controller, this is my method**
public string Loadmyaction(string obj)
{
string str = "";
return str;
}
Here obj is getting null from the view. Why is that no data is being passed back to the controller ?
Are you sure it's actually hitting your method?
Your jquery should look like this:
$.ajax({
type: "POST",
url: "<%=Url.Action("Loadmyaction") %>",
data: $("#upModel").serialize(),
dataType: "json",
success: function(data) {
alert(data);
},
error: function(result) {
alert("Error" + result);
}
});
Try changing your parameter type to myClass, whatever it might be.
[HttpPost]
public JsonResult LoadMyAction(MyClass model)
{
return Json("someString");
}
Related
The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method.
Here how can pass selected file as HttpPostedFileBase in the below ajax method.
`
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
$(function () {$("#fileupload1").change(function () {
$("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));
var file = $("#spnName").html();
$.ajax({
url: "UploadExcelForContractStaff",
type: 'POST',
data: JSON.stringify({ file: file }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
});
});`
[AcceptVerbs(HttpVerbs.Post)]
public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
//A 32-bit provider which enables the use of
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
{
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
//DataSet ds = new DataSet();
adapter.Fill(ds, "Items");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//Now we can insert this data to database...
}
}
}
}
}
}
}
catch (Exception ex) { }
return "";
}
I got solution. changed code like
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
</form>
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) { }
});
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{return Json();
}
I have modified original modal.js script to support ajax content as well, and added a new Behavior called "ajax" here is my piece of code:
ajax: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
var $content = $(this).find('.content');
$.get("contentData.php", function(data) {
$content.html(data);
});
And I call it like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax')
});
The above code works perfect and loads content correclty, but I would like to extended a bit more, so I can include additional info such as custom url, dataType, etc pretty much all the ajax options, and I would like to do that from initialization part like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax', {"id":5}, dataType:"json", "url": http://myurl.php" etc...)
});
A bit late but this it what's working for me:
$('body').on('click', '.domOdal', function (e) {
e.preventDefault();
$('.ui.modal')
.modal({
blurring: true,
observeChanges: true,
transition: 'scale',
onVisible: function (callback) {
callback = $.isFunction(callback) ? callback : function () { };
var $content = $(this).find('.content');
$.get("contentData.php", function (data) {
$content.html(data);
});
}
}).modal('show')
});
And in your html where the modl is called:
<div class="ui modal">
<i class="close icon"></i>
<div class="content">
</div>
</div>
How about doing it like this:
$('body').on('click', '.domOdal', function() {
$.ajax({
url: "specs.html",
type: 'POST',
dataType: 'xml',
dataType: 'html'
}).done(function(response) {
console.log(response)
$(response).modal();
});
});
I've worked on this but couldn't fully figure out.
Basically, what I need is to upload 2 or more files separately (only on demand one by one, not all files at once) using Ajax upload. Currently, I have 2 file inputs but somehow, the JavaScript code always uploads the first file input (the one inside "formContentProperty").
Here is my HTML code:
<div>
<form enctype="multipart/form-data" id="formContentProperty">
<input id="fileContentProperty" type="file" name="fileContentProperty" />
<a id="uploadbuttonContentProperty" href="javascript:void(0)">
<span>Upload 1</span>
</a>
</form>
<progress></progress>
</div>
<div>
<form enctype="multipart/form-data" id="formContentPreviewImage">
<input id="fileContentPreviewImage" type="file" name="fileContentPreviewImage"/>
<a id="uploadbuttonContentPreviewImage" href="javascript:void(0)">
<span>Upload 2</span>
</a>
</form>
<progress></progress>
</div>
Here is my JavaScript code:
$('#uploadbuttonContentProperty').click(function () {
return UpdoadFile('formContentProperty', 'divUploadContentPropertyResultMessage');
});
$('#uploadbuttonContentPreviewImage').click(function () {
return UpdoadFile('formContentPreviewImage', 'divUploadContentPreviewImageResultMessage');
});
function UpdoadFile(formElementId, divMessageElementId) {
var formData = new FormData($('form')[0]);
$.ajax({
url : '<%= base.AjaxUploadHandlerPath %>', //Server script to process data
type : 'POST',
xhr : function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//beforeSend: beforeSendHandler,
success : function(response) {
var obj = $.parseJSON(response);
$('#' + divMessageElementId).html(obj.ResultMessage);
},
//error : errorHandler,
data : formData,
//Options to tell jQuery not to process data or worry about content-type.
cache : false,
contentType : false,
processData : false
});
};
function progressHandlingFunction(e){
if(e.lengthComputable)
$('progressContentProperty').attr({ value: e.loaded, max: e.total });
}
I'd really appreciate any help.
To upload files using ajax file upload
<script>
function uploadFiles()
{
var files = $('#previewFile')[0].files;
var totalFiles = files.length
for(var i=0; i < totalFiles; i++)
{
var formData = new FormData();
formData.append("previewFile",files[i]);
doAjaxFileUpload("/storeTempFile.do", formData,function(data)
{
data = eval(data);
if (data.result=="success")
{
alert("File uploaded successfully");
}
else
{
alert("Error occured : "+data);
}
},
function(data)
{
alert("Error occured : "+data);
});
}
}
function doAjaxFileUpload(actionURL,params,callbackSuccessFunction,callbackFailureFunction)
{
$.ajax(
{
url: actionURL,
type: "POST",
data: params,
processData: false,
contentType: false,
error: callbackFailureFunction,
success : callbackSuccessFunction
});
}
</script>
My Zend controller is like below:
public function deleteAction()
{
$this->_helper->layout->disableLayout();
$id = (int)$this->_request->getPost('id');
$costs = new Application_Model_DbTable_Costs();
if($costs->deleteCosts($id)){
$this->view->success = "deleted";
}
}
And ajax call I ma using to post data is :
$.ajax({
dataType: 'json',
url: 'index/delete',
type: 'POST',
data:id,
success: function () {
alert("success");
},
timeout: 13*60*1000,
error: function(){
console.log("Error");
}
});
And in my delete.phtml the code is like:
<?php
if($this->delete === true):
echo 'true';
else:
echo 'Sorry! we couldn\'t remove the source. Please try again.';
endif;
?>
The response is returning the html.
Its my first project with Zend Framework.
Thanks in advance.
Your controller action is returning HTML, not JSON.
You should consider using the AjaxContext action helper
public function init()
{
$this->_helper->ajaxContext->addActionContext('delete', 'json')
->initContext();
}
public function deleteAction()
{
$id = (int)$this->_request->getPost('id');
$costs = new Application_Model_DbTable_Costs();
try {
$costs->deleteCosts($id));
$this->view->success = "deleted";
} catch (Exception $ex) {
$this->view->error = $ex->getMessage();
}
}
The only other thing you need to do here is supply a format parameter of json in the AJAX request, eg
$.post('index/delete', { "id": id, "format": "json" }, function(data) {
if (data.error) alert("Error: " + data.error);
if (data.success) alert("Success: " + data.success);
}, "json");
You may want to handle the response differently but that should give you an idea.
how can i load second dropdown on selection of first and third on second. in asp.net mvc 2
I have the dropdown trigger an ajax post that sends the selected ID selected to a controller and then return a partial view which overwrites the html for a placeholder div.
View; this sets the ActionUrl, you will also need a placeholder div (in my case called departments) for the drop down to be injected:
<script type="text/javascript">
var ActionUrl = '<%= Url.Action("RenderDepartments", "ControllerName") %>';
</script>
<script src="<%: ResolveUrl("~/Scripts/Custom/DepartmentFilter.js")%>" type="text/javascript"></script>
<%: Html.DropDownListFor(model => model.OfficeId, Model.ListItems, "-- Please Select --", new { onchange = "GetDepartments()" })%>
// ^^ ON CHANGE IS IMPORTANT ^^
<div id="departments"></div>
JQuery;
function GetDepartments() {
$.ajax(
{
type: "POST",
url: ActionUrl,
data: { officeId: $("#OfficeId").val() },
success: function (data) {
$("#departments").html(data);
}, error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('XMLHttpRequest:' + XMLHttpRequest.responseText);
alert('textStatus:' + textStatus);
//alert('errorThrown:' + errorThrown);
}
});
}
Controller Action;
public ActionResult RenderDepartments(int? officeId)
{
if (officeId.HasValue)
{
var departments = new SelectList(ents.GetDepartments(officeId), "departmentID", "Name");
var model = new DropdownListViewModel(departments);
return PartialView("DepartmentDropdown", model);
}
return null;
}
This is nullable because the user could submit "-- please select --" which will in this case return null and remove the departments dropdown.