How to refresh a particular division while using MVC - c#

I have tried different ways to refresh a particular division in MVC.
1. Using HTML Action Link
2. Ajax Action Link
3. method
Please help me resolve this issue.
My Code is as follows:
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function updateAsyncCategoryUpdate() {
var url = '/Home/HomePage';
$.ajax({
url: url,
//data: { value: '1234' }, //if there are any parameters
dataType: "html", //or some other type
success: function () {
window.location.reload(true);
// or something in that area, maybe with the 'data'
},
error: function () {
//some derp
}
});
}
</script>`
#Ajax.ActionLink(item.Name, "HomePage", new { CATEGORy = item.Name }, new AjaxOptions {HttpMethod="GET", OnSuccess = "updateAsyncCategoryUpdate('item.Name')" })

You can append the success function.
This replaces content of div
success: function (data)
{
$('#divSelector').html(data);
}
This appends content of div
success: function (data)
{
$('#divSelector').append(data);
}

Your script function does not have parameter and you send Item.Name to it.(although you dont use this parameter inside the script!)
First, define parameter for updateAsyncCategoryUpdate function.
Secomd,Add a container element(like div) to your page with specific id(resultDiv for example) and replace the success code of your scrip with this:
success: function(result){
var myDiv = $('#resultDiv');
myDiv.empty();
myDiv.prepend(result);
}

Related

asp-all-route-data not calling action method in Asp.Net Core MVC

I am running Asp.Net Core 3.1 application where i have one left side menu in layout which i load through partial view.
To set menu link i used the anchor tag like below:
var allRouteData = new Dictionary<string, string>
{
{ "menuid", mID.ToString() },
{ "isCalledByMenu", "true" },
{ "where", "tab" }
};
<a class="#clas" data-ajax="true" data-ajax-complete="RedirectToPage('#M.MenuUrl', '#M.MenuName',true)" data-ajax-mode="replace" data-ajax-update="#myTab" asp-action="GetSubMenu" asp-controller="Base" asp-all-route-data="#allRouteData">#M.MenuName</a>
So when page loads then HTML generate like below:
<a class="nav-link btn fuse-ripple-ready" data-ajax="true" data-ajax-complete="RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services',true)" data-ajax-mode="replace" data-ajax-update="#myTab" href="/Base/GetSubMenu?menuid=9630&isCalledByMenu=true&where=tab">Professional Services</a>
Below is action method used :
public IActionResult GetSubMenu(int menuid, bool? isCalledByMenu, string where = null)
{
return ViewComponent("SubMenu", new { menuid = menuid, isCalledByMenu = isCalledByMenu, where = where });
}
In Layout page on the top i assigned the tag helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
But when i click on the link it is not hitting this action method.
Update: When i click menu then first it hit the list inside javascript where i do some ajax call:
$('#myTab>li>a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
e.preventDefault();
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
In SetCurrentPageNameSession method i do ajax call to set the menu name in server side to some session before calling action method.
like below:
function SetCurrentPageNameSession(CurrentPage, IsBookMark) {
if (IsBookMark==undefined)
IsBookMark = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark },
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
Then after it anchor tag call the action method.
Please suggest.
Maybe you could forget data-ajax, it also doesn't work on me and I can't find the answer about it. You could code as below and it also can request the GetSubMenu and continue to excute next logic.
<div id="myTab"></div>
<a class="nav-link btn fuse-ripple-ready"
href="#">Professional Services</a>
<script>
$('a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
//e.preventDefault();
$.ajax({
url: "/Base/GetSubMenu",
async: true,
type: "get",
datatype: "json",
data: #Json.Serialize(allRouteData),
success: function (result) {
$('#myTab').html(result)
}
});
//RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services', true);
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
</script>
Comment or Remove e.preventDefault();
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
I found the solution for the above asked question:
The issue was when i click on menu link then i used to call first it's anchor click in javascript where i did e.preventDefault() and then used to do some ajax call to pass some value to set in session. Due to e.preventDefault() call after that it was not hitting the action method.
Since i had to pass other three data to server to set somewhere. To do that i set all three value in anchor tag data-link attribute separated with Pipe like below:
data-link="9630|true|tab|/OrgOverview/ProfessionalServices|Professional Services"
function SetCurrentPageNameSession(CurrentPage, IsBookMark, MenuID, IsCalledByMenu, Where, PageUrl, PageName) {
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark, menuID: MenuID, isCalledByMenu: IsCalledByMenu, where: Where},
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
if (PageUrl != undefined && PageUrl != '' && PageUrl != null)
RedirectToPage(PageUrl, PageName, true, false)
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Then in this ajax call success i am redirecting the page with passed page url.
But still i am wondering the same code how it was working in MVC and not in asp.net core.
That's it.

Passing array from view to controller using Ajax but, on action, array shows as empty

I am passing an array from view to controller using Ajax but, on action, the array shows empty.
This is my code:
View
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values: arr["48","47","46"] },
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Action
public ActionResult array(string[] Values)
{
for (int id = 0; id < Values.Length; id++)
{
string newID = Values[id];
}
return View();
}
jQuery.ajaxSettings.traditional = true;
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values:["48","47","46"]},//just edit this line
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Your code has some issues regarding how you are sending the data! What is your expectation when you execute this expression arr["48","47","46"] ????? That is going to give you undefined and that is what you are trying to send!
There are two ways to fix your code. You can send the array in the request body. For this, you need create a JSON string from the array and send that as the data property while explicitly specifying the request content-type header value as "application/json". You may use the JSON.stringify method to get the JSON string of your js array.
Also, make sure you are making the call to the correct action method. In your question you shared the array action method code, but in your client side script you were trying to call a different action method(`Checkboxes)!
This should work.
var arry = ["48", "47", "46"];
var url = "#Url.Action("array", "Main")"; // Update your real url here
// If your script is inside the razor view, you can us Url.Action (c#) method
$.ajax({
type: "Post",
url: url ,
data: JSON.stringify(arry),
contentType: "application/json",
success: function(r) {
alert("Success");
console.log(r);
},
error: function() {
alert("error");
}
});
Another option is to send a javascript object with Values property (which has the array as the value of it) as the data property value of the $.ajax call. Now the request content-type header will be application/x-www-form-urlencoded; and the array will be sent as FormData in the request.
var arry = ["48", "47", "46"];
$.ajax({
type: "Post",
url: "/Main/array",
data: { Values: arry },
success: function(r) {
console.log(r);
},
error: function() {
alert("error");
}
});

Ajax call Parameter does not accept #Model as parameter value

I have following code which is making an Ajax call from a .CSHTML file.
<script type="text/javascript">
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});
</script>
My VS shows syntax error. But instead of #Model.EmployeeId if I hardcode it to any int value like 1 then it works fine.
Now #Model.EmployeeId is not NULL and it is an int. It is just that Ajax does not like it. Any idea why? Should I not be using #Razor components in Ajax calls?
To use Razor in JS, wrap the attributes in '',
data : '#Model.EmployeeId',
//For passing integer use parseInt('#Model.EmployeeId') or Number('#Model.EmployeeId')
and
var model = {
EmployeeId: '#Model.EmployeeId',
....
};
The quotes act as delimiters, so the Razor parser recognizes the values.
or Alternatively,
data : #Model.EmployeeId + "",
It's just a bug in Visual Studio, the view should works as excepted.
The answer was explained here: Razor/JavaScript and trailing semicolon.
If you don't like it, you can just put the "plus zero" after the #Model
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId + 0,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId + 0,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});

Auto Complete in Razor MVC.NET [duplicate]

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

jquery AJAX sent data in key value pair

In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});

Categories