ActionLink to HttpPost action method - asp.net-mvc

I have this link on my page:
#Html.ActionLink("Like", "Like", "Like", new {likeId = i.ItemId}, new {id = #i.ItemId, #class = "likeButton"})
This is my ajax call:
$(document).on("click", ".likeButton", function (event) {
var itemId = event.target.id;
$.ajax({
url: this.href,
type: 'POST',
data: { item: itemId },
context: this,
success: function (result) {
...
return false;
});
And it works when action metohd is like:
public ActionResult Like(int itemId)
...
But if I decorate method with [HttpPost] It doesn't work.
Can this be achieved?
Also what security issue can be if I don't add [HttpPost]?

Try this:
$(document).on("click", ".likeButton", function (event) {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
...
return false;
});
You are passing item.Id twice, first in url and second in body. when using post method, you can still pass parameters through url. passing parameters with body is good when you want to hide these parameters.
And one more thing, you can use Ajax.ActionLink in this case (because it is created for this kind of cases)
And you have mistake:
data: { item: itemId }
Should be:
data: { itemId: itemId },

Related

Partial View not showing updated model values. Always shows existing values

Actually i tried to update the partial view content whenever i do search. So i use ajax call to achieve this. So, the values from the controller to partial view model is correct(new data), but its not binding to the view (shows existing data).
Main View
<div class="tab-pane active" id="partialviewpage">
#{
Html.RenderPartial("_Details", Model);
}
</div>
Partial View (_Details)
foreach (var item in Model.AllAds)
{
//div contents
}
Ajax Call
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Category Controller
public ActionResult Subcategory(string item)
{
//Logic calling Api content goes here
var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JssSearch = new JavaScriptSerializer();
List<Result> Jsonresult = (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
var Model= new ModelName();
{
Model.AllAds = new List<Result>();
Model.AllAds = Jsonresult;
}
return PartialView("_Details", Model);
}
So, What's wrong with my code and how can i modify the code to get the new model values. Any help appreciated. Thanks in advance.
I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});

IE -10 -Ajax get method not hitting Controller

$http({
method: 'GET',
dataType: 'json',
url: 'Calendar/GetDate',
params: { calenderId: $scope.CalendarId, fyYear: new Date(viewValue).toUTCString()
}
}).success(function (result) {
alert(result);
});
Below value getting returns, and its not calling the controller method
[UMAuthorize]
public ActionResult GetDate(string calenderId, DateTime fyYear)
{
.......
.....
return Json(new { startDate }, JsonRequestBehavior.AllowGet);
}
You are posting data to controller so I guess you should put the attribute HttpPost as shown below :-
[UMAuthorize]
[HttpPost]
public ActionResult GetDate(string calenderId, DateTime fyYear)
{
.......
.....
return Json(new { startDate }, JsonRequestBehavior.AllowGet);
}
and from you are calling controller make it a Post method instead of Get as shown below :-
$http({
method: 'POST',
dataType: 'json',
url: 'Calendar/GetDate',
params: { calenderId: $scope.CalendarId, fyYear: new Date(viewValue)
}
}).success(function (result) {
alert(result);
});
and ur fyYear object is DateTime in controller but you are converting it into string and then sending so its not matching the parameters of controller
I susupect the the url passed is wrong, use Url.Action() helper for generating correct url:
change:
url: 'Calendar/GetDate'
to:
url: '#Url.Action("GetDate","Calendar")'

jquery ajax load partial view to div tag MVC

I've been searching around with no luck on how to make a jquery call to load a partial view in a div tag on my Index view. Some how I am not getting the partial view to update when I click on a link on my tree. The partial view loads when I first run it b/c I call <div id="divid">
#Html.Partial("_InnerView")</div>. After that nothing happens when I click on the link. Or maybe I am not getting the full picture here. Some mentioned to use $('#divid').load = data; or $('#divid').innerHTML= data; but nothing works for me. This is what I have.
Controller:
public ActionResult Test(string parentEls)
{
if (Request.IsAjaxRequest())
{
Employee employee = new Employee();
employee.Name = parentEls + "1";
return PartialView("_InnerView", employee);
}
return View("_InnerView");
}
Index view:
<div id="divid">
#Html.Partial("_InnerView")</div>
$('#tree a').click(function () {
var parentEls = $(this).parents('ul').map(function () {
return $(this).find('a').first().text();
}).get().join(", ");
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
});
_InnerView.cshtml:
#model TreeDemo.Models.Employee
EmpName:#Model.Name
UPDATE: I got this to work with this
$.ajax({ url: '/Home/Test/', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'html', data: { parentEls: parentEls } })
You have to use
$('#divid').html(data);
instead of
$('#divid').innerHTML = data;
Load Partial View in a div MVC 4
Recently I want load Partal View in Div , after doing lots of R&D and It's work for me
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: {
title: title
},
success: function(result) {
$('#divid').innerHTML = result;
}
});
And In Partal View Action Controller Code
public PartialViewResult ShowCategoryForm(string title)
{
Model model = new Model();
model.Title = title;
return PartialView("~/Views/ControllerName/PartalView.cshtml", model);
}
I think it can be useful if you check the request/response objects of your call, so you can see what is really happening after you make the call... As per your code, I can notice that you're posting using
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
but your action is marked for 'getting'... you'd need to have something like this
[HttpPost]
public ActionResult Test(string parentEls)
so MVC can understand that the action should be called when HttpPost verb is used

MVC bind Json collection of objects to controller action

is there a way to send a collection of objects to MVC action?
View:
$(".iconDocumentText").click(function (e) {
e.preventDefault();
var $inputs = $("form.form :input:not('.submit')");
var values = {}; // get search form values
$inputs.each(function () {
if ($(this).val()) {
values[this.name] = $(this).val();
}
});
console.log(JSON.stringify(values));
$.ajax({
url: "#Url.Action("Export","Log")",
data: JSON.stringify(values),
contentType: 'application/json',
type: 'GET',
success: function (data) {
.........
}
});
});
I tried this without any luck:
public ActionResult Export(Dictionary<string, string> values)
{
....
this is what's being sent to controller action:
{"f_device":"4","f_package":"AGI-VS-GAME-M52-1.5.3.2.67"}
You have also to indicate that it is of datatype json and pass them directly:
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: values,
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(int f_device, string f_package)
{
EDIT :
But if you want to retrieve a dictionary, you can encapsulate your data in an object :
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: { values : values },
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(Dictionary<string, string> values)
{

jQuery Ajax call to controller

I'm new to Ajax and I'm trying to disable a checkbox if certain items are selected in a dropdown. I need to pass in the mlaId to the GetMlaDeliveryType(int Id) method in the RecipientsController.cs.
I'm not exactly sure how to set up the ajax call in the javascript function checkMlaDeliveryType(mlaId).
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
var deliveryType = checkMlaDeliveryType($('.AddSelectedMla').val());
// disable express option if delivery type is Electronic
if (deliveryType == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
}else{
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: "GET",
url: "/Recipients/GetMlaDeliveryType/" ,
data: mlaId,
dataType: ,
success:
});
}
RecipientsController.cs
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return recipientOrchestrator.GetMlaDeliveryTypeById(Id);
}
EDIT:
Here's how the final javascript looked that worked
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
checkMlaDeliveryType($('.AddSelectedMla').val());
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: 'GET',
url: '#Url.Action("GetMlaDeliveryType", "Recipients")',
data: { id: mlaId },
cache: false,
success: function (result) {
// disable express option if delivery type is Electronic
if (result == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
} else {
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
}
});
}
$.ajax({
type: 'GET',
url: '/Recipients/GetMlaDeliveryType',
data: { id: mlaId },
cache: false,
success: function(result) {
}
});
then fix your controller action so that it returns an ActionResult, not a string. JSON would be appropriate in your case:
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return Json(
recipientOrchestrator.GetMlaDeliveryTypeById(Id),
JsonRequestBehavior.AllowGet
);
}
Now your success callback will directly be passed a javascript instance of your model. You don't need to specify any dataType parameters:
success: function(result) {
// TODO: use the result here to do whatever you need to do
}
Set data in the Ajax call so that its key matches the parameter on the controller (that is, Id):
data: { Id: mlaId },
Note also that it's a better practice to use #Url.Action(actionName, controllerName) to get an Action URL:
url: '#Url.Action("GetMlaDeliveryType", "Recipients")'

Resources