controller is not geting view data - asp.net-mvc-3

function export(){
$.ajax({ url: "#Url.Content("~/controllr/method")",
type: 'GET',
data: { selectedValue : $("#BranchId option:selected").text() },
traditional: true,
async:false,
success: function (result ) {
},
failure: function () {
failed=true;
alert("Error occured while processing your request");
},
error: function (xhr, status, err) {
failed=true;
alert("Error occured while processing your request");
}}

Did you try setting a breakpoint on the controller action and see whether its is being hit ? Please try the following basic code and see whether the call is getting through
$.ajax({
url: ‘#Url.Content(“~/MyController/MyMethod”)’,
type: ‘post’,
data: {
selectedBranchId : $("#BranchId option:selected").text()
}
});
// I am the controller action
public ActionResult MyMethod(string selectedBranchId)
{
// your code
}
Please note I have dropped all the callback code and changed the controller name and the action name with the name of the postback variable

Related

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

When i call ajax there url wrong why?

I have a one Edit.cshtml page and there is 1 partial template call. in that template I make an ajax call and my controller is home and action name is savedata
ajax function
$.ajax({
url: "CountryZone/SaveData",
type: 'POST',
data: { data: selectedID, id: id },
dataType: "html",
success: function (result) {
alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
controller:--
public ActionResult Savedata(string data, int CountryZoneId)
{
return null;
}
now when my ajax call is going
there is url wrong :--- url is Home/edit/Home/Savedata instead of this there is only Home/SaveData
It's a bad idea to hardcode urls in MVC application.
Change this line:
url: "CountryZone/SaveData",
To this:
url: "/CountryZone/SaveData",
I suggest at least using Url.Action in the view and storing it in the js variable.
Use standard MVC code as below:
url: '#Url.Action("SaveData","CountryZone")',
Full Code
$.ajax({
url: '#Url.Action("SaveData","CountryZone")',
type: 'POST',
data: { data: selectedID, CountryZoneId: id },
dataType: "html",
success: function (result) {
alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
[HttpPost]
public ActionResult Savedata(string data, int CountryZoneId)
{
return null;
}

How to handle FileStream return type in .ajax post?

I am sending JSON object through following code.. Controller returning values in CSV format that should be provide promt to open or save as CSV file. I unable to understand that what exactly code should be write in success: function (result)
Link for Export
Html.ActionLink("Export", "", "", null, new { #onclick = "return exportData();"})
function exportData() {
var searchViewModel = getExLogSearchModelData();
var path = getAbsolutePath("ExclusionLog", "ExportData");
$.ajax({
url: path,
cache: false,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
data: JSON.stringify(searchViewModel),
success: function (result) {
},
error: function (error) {
$("#voidcontainer").html("Error");
}
});
}
Controller ActionResult
public ActionResult ExportData(ExclusionLogSearchViewModel postSearchViewModel)
{
try
{
IEnumerable<ExclusionLogViewModel> exclusionLogData = null;
exclusionLogcData = this._workerService.GetExclusionLogData(postSearchViewModel);
return CSVFile(exclusionLogMembershipSyncData.GetStream<ExclusionLogViewModel>(), "ExclusionLogTables.Csv");
}
catch (Exception ex)
{
throw ex;
}
return null;
}
Can you please suggest how to do this?
I've hit the same problem and I didn't find a way to download file using $.ajax but I found an excellent JavaScript library that provides similar behavior:
https://github.com/johnculviner/jquery.fileDownload
You just need to invoke something like this:
$.fileDownload(path, {
httpMethod: 'POST',
data: JSON.stringify(searchViewModel),
success: function (result) {
},
error: function (error) {
$("#voidcontainer").html("Error");
}
});
And remember to create cookie in controller. In src/Common there is suitable action filter that do it for you.

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources