I have the following code:
#Html.PagedListPager(Model, page => Url.Action("Index", new {from = ? , to = ? , page}))
And this is my Action method:
public ActionResult Index(string from, string to, int? page)
{
}
I want to specify the from and to parameters that comes from a picker which are defined as below:
#Html.EditorFor(c => c.LastOrDefault().Date, "MyPickerTemplate")
#Html.EditorFor(c => c.FirstOrDefault().Date, "MyPickerTemplate")
How can I send the value of the EditorFor's as a parameter to Url.Action? I can find them with javaScript like below:
var from = document.GetElementByClassName("date")[0].value;
var to = document.GetElementByClassName("date")[1].value;
But I don't know how should I send them as parameter to Url.Action.
var from = document.GetElementByClassName("date")[0].value;
var to = document.GetElementByClassName("date")[1].value;
Now you have two parameters. You can call ajax function as below.
$.ajax({
url: "/Controller/TheAction",
type: "get",
data: { fromParam: from, toParam: to }
});
Here is the controller,
public ActionResult TheAction(DateTime fromParam, DateTime toParam)
{
// your code.
}
EDIT:
You must call ajax from pager button click. For that, do following.
<div id="myPager">
#Html.PagedListPager(Model, Page => "")
</div>
<script type="text/javascript">
$(function () {
$('#myPager').on('click', 'a', function () {
var currentPage = $(this);
// ajax call
});
});
</script>
Related
I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})
I have a table for departments. Right now I created controller for every department and every department have index.cshtml.
But they use the same functions. I hard coded their departmentId in every index page.
for example for department IT with departmentId = 1
public class ItController : Controller
{
// GET: It
public ActionResult Index()
{
return View();
}
}
And in It's index page I have hard coded with decleration var id = 1; Like this
<div class="panel panel-body">
<div class="col-md-4 table-responsive" id="productsTable"></div>
</div>
<script type="text/javascript">
var id = 1; // for the department that id is 1 so I have to create index for every department and hard code like this
function AllProductsByDepartmentId(id) {
var tbl = $('#productsTable');
$.ajax({
cache: false,
url: '/Home/GetAllProductsByDepartmentId?id=' + id,
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
tbl.empty().append(result);
},
error: function () {
}
});
}
</script>
But to do like this is not good becouse if by some reasen changes Id of department or when I create a new department next time then
I have to hard coded again ...
What I want is first I want to populate those departments in my _Layout dynamicaly from database.
So I created controller
public class DepartmentsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Departments
public async Task<ActionResult> Index()
{
return View(await db.Departments.ToListAsync());
}
}
And this is my PartialView of Departments and I want to populate it in _Layout.cshtml, but I don't know how to do and how to link them to a function ...
#model IEnumerable<Inventory.Models.Departments>
#foreach (var item in Model) {
#Html.ActionLink(modelItem => item.DepartmentName???????, ??????, ?????, new { id = item.DepartmentId })
}
and link them to this java function
function AllProductsByDepartmentId(id)
{
// ......
}
I think I have to create another common controller to have an index page to all departments.But How to create actionlinks dynamicaly and link them to javascript function. Thank you in advance!
There is no need to use #Html.ActionLink() to generate links in this case. You foreach loop can be just
#foreach (var item in Model) {
#item.DepartmentName
}
Note that the value of DepartmentId is added to the link as a data attribute.
Then you script would be
var url = '#Url.Action("GetAllProductsByDepartmentId", "Home")';
var tbl = $('#productsTable');
$('.details').click(function() {
tbl.load(url, { id: $(this).data('id') });
});
I place a text box in the bootstrap modal popup and also I have a kink in the table data in the table come from database so I want when I click pop-up show database cell value in the textbox that exists in the modal-popup. Below is my code
Thats my action method that gets data and data is passing to the ViewBag.Type
public JsonResult LinkButton(int RoelID)
{
Role model = new Role();
Session["State"] = RoelID;
int id = RoelID;
RoleServices ser = new RoleServices();
var data = ser.Get(id);
bool result=false;
if(Session["State"]!=null)
{
ViewBag.Type = data.RoleType;
result=true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is a code of JQuery and Ajax acall the action method on link click
Select
<script>
var UpdateID = function (RoelID) {
$("#hiddenID").val(RoelID);
var roleID=$("#hiddenID").val();
$.ajax({
type: "post",
url: '#Url.Action("LinkButton", "Account")',
data: { RoelID: roleID },
success:function()
{
$("moReg").modal('hide');
}
})
$("#moReg").modal('show');
}
</script>
Here is textBox in the Modal PopUp
#Html.TextBoxFor(model => model.RoleType, new { #value=ViewBag.Type })
You can return your data like bellow,
return this.Json(new { result = true, Type = data.RoleType },
JsonRequestBehavior.AllowGet);
Then in your ajax success method, you can retrieve the value like,
success:function(data)
{
var _result = data.result;
var _Type = data.Type ;
}
I have wrote an AJAX post request to my deletewidget controller, it is posting the request token fine, however it does not seem to pass the widgetID to the controller. I have stepped through the javascript code and it assigns the ID to the variable widgetID fine, and have also put a breakpoint in my controller but it says null.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
//get the form
var form = $('#__AjaxAntiForgeryForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
//we make an ajax call to the controller on click
//because the controller has a AntiForgeryToken attribute
//we need to get the token from the form and pass it with the ajax call.
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
success: function(result){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact admin");
}
})
}
return false;
})
});
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WidgetModel widgetModel = db.widgets.Find(id);
db.widgets.Remove(widgetModel);
db.SaveChanges();
return new EmptyResult();
}
It seemed to be executing the ajax code twice, I moved my return false up one level and it solved the problem
Hi sorry for asking such an easy question but I'm scratching my head all day today and cannot figure this out. I found lots of similar questions but non of them resolve my problem.
I had a page with list of products and few buttons to filter products by category. Because number of products has increased I decided to change them to drop down box.
So I have drop down box which populates categories:
#Html.DropDownListFor(m => m.SelectedCategoryId, Model.CategoryItems, new { id = "changeCategory" })
and javascript which fires on change event:
<script type="text/javascript">
$(document).ready(function () {
$("#changeCategory").change(function () {
var selectedCategory = $(this).text();
$.ajax({
url: '#Url.Action("List", "Deal")',
type: 'GET',
data: { category: selectedCategory },
cache: false,
});
});
});
</script>
This doesn't work. My previous routing works with the code below:
#foreach (var link in Model) {
#Html.RouteLink(link, new {
controller = "Deal",
action = "List",
category = link,
page = 1
}, new {
#class = "btn btn-block btn-default btn-lg"
})
}
UPDATE:
I have changed the jQuery code to:
<script type="text/javascript">
$(document).ready(function () {
$("#changeCategory").change(function () {
var selectedCategory = $("#changeCategory option:selected").text();
$.ajax({
url: selectedCategory,
type: 'POST',
cache: true,
});
});
});
</script>
and the link looks correct now but the website doesn't reload. When I watch this in the Chrome Developer Tool in Network section the link appear there and when I click it it does open correct page.
Why it doesn't do that on website?
UPDATE 2
My Controller
public ViewResult List(string category, int page = 1)
{
DealsListViewModel model = new DealsListViewModel
{
Deals = repository.Deals
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.DealID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Deals.Count()
},
CurrentCategory = category
};
return View(model);
}
Any help is appriciated
It appears you want to redirect to the List method of DealController and pass the text of the selected option. If so then
$("#changeCategory").change(function () {
window.location.href = '#Url.Action("List", "Deal")' + '/' + $(this).find('option:selected').text();
});
assuming your action method is something like
public ActionResult(string someValue)
AJAX calls stay on the same page and do not redirect to another page.
And out of curiosity, why override the default id (and not just use $("#SelectedCategoryId").change(...)?
Edit
If you want to return some html to include on the page, return a partial view and update the page html in the AJAX success function
Controller
public PartialViewResult List(string category, int page = 1)
{
DealsListViewModel model = new DealsListViewModel ....
....
return PartialView(model)
}
Script (assumes you have an element with `id="results" where you want to render the returned html)
$("#changeCategory").change(function () {
var url = '#Url.Action("List", "Deal")';
var category = $(this).find('option:selected').text();
var page = ? // if you want to pass this as well
$.get(url, { category: category, page: page }, function(data) {
$('#results').html(data);
});
});
Try the following in your ajax call:
type: 'POST'