My ajax post,
function getuser() {
if (window.user == undefined) {
$.ajax({
type: "POST",
url: url, // value from view file(var url = "#Url.Action("getuser", "home")";)
data: { },
async: false,
cache: false,
success: function (result) {
window.user = result.data.user;
}
});
}
}
My controller,
[Authorize]
public class HomeController
{
[HttpPost]
public JsonResult GetUser()
{
return this.Json(new { data = GetUser() });
}
}
I have removed async: false also. But my controller method is not triggering. Please correct me where I am wrong ?
Related
I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null
Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}
please your help to call a method from controller using ajax request, below is my code, but error had returned says that the source of controller cannot be found.
here is my ajax code
function GetServices() {
var e = document.getElementById("catagories");
var strUser = e.options[e.selectedIndex].value;
var id = e.options[e.selectedIndex].id;
$.ajax({
url: "~/VasController/ExecuteVas/",
//url: '<%= Url.Action("GetServices", "Vas") %>',
type: 'POST',
contentType: 'application/json',
data: {"id": id},
success: function (result) {
alert(result);
}
});
}
and here is my controller method
[WebMethod]
public static string GetServices(string id)
{
return id;
}
kindly advice, i am still beginner in c# and MVC
in your controller file
public class YourControllerNameController : Controller
{
[HttpPost]
public ActionResult Dosomething(int? id)
{
//your code
return View();
}
}
then in your view
$.post('#Url.Action("Dosomething","YourControllerName")', { id: id }, function (data) {
});
You have to do the following:
1- Decorate the Action method with [HttpPost] tag
2- Remove the word 'controller' for the Ajax URL it would be 'url: "~/Vas/ExecuteVas/"
3- if 1 and 2 did not work,Try putting the Ajax URL without ~/
I am working on an mvc project. In a Home controller i have an action which is called GetCityByID which takes id and checks the db for a city and returns city name.
In My View, I want to call this action and get a result and display it.
Can someone please demonstrate different ways of doing this?
i think i could through ajax/javascript, also through #url.Action ?
Yes, you can make ajax call to controller method from view. Following will be the JS code.
$.ajax({
async: false,
cache: false,
type: "GET",
url: "#(Url.Action("YourAction", "YourController"))",
data: { "id": ui.item.Id }, //Param
success: function (data) {
}
});
MVC code in controller.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ActionName(int id)
{
....Your Code....
return Json(model);
}
In View :
$.ajax({
async: false,
cache: false,
type: "GET",
url: "#(Url.Action("YourAction", "YourController"))",
data: { "id": ui.item.Id }, //Param
success: function (data) {
}
});
MVC Controller Code:
[HttpGet]
public JsonResult ddlSurgeryDescription(string id)
{
Do Process Here
return Json(new { id = ViewData["ddlSurgeryDescription"] }, JsonRequestBehavior.AllowGet);
}
I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});
I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller