I am trying to add attributes like ID into pagination so I can perform some actions in JS on behalf of that.
#Html.PagedListPager(Model, page => Url.Action("ConfirmCases", new { page }))
when I tried to add it shows in the URL. Does anybody know how I can set an ID in this case?
any helps regarding this would be appreciated.
I figured it out.
#Html.PagedListPager(Model, page => Url.Action("ConfirmCases", new { ID = ViewContext.ViewBag.CheckingAccountId, page, PageSize = Model.PageSize } ))
ViewContext needed to be added in order to get the ID from the viewbag... and also declared the id again in the controller.
OR
Using JQuery
<div id="Paginator">
#Html.PagedListPager(Model, page => Url.Action("ConfirmCases", new { ID = ViewContext.ViewBag.CheckingAccountId, page, PageSize = Model.PageSize } ))
</div>
Jquery Function
function bind() {
$('#Paginator').on('click', 'a', function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
$('#TableContainerId').html(result);
bind(); // called this java script code again
}
});
return false;
});
});
Related
I have a nav bar with two buttons. Each button renders a view. I am using Jquery to dynamically load those views in one View which then gets rendered on the layout page. That means I am rendering all my views dynamically in one index page.
However, I end up losing the url history and it's not possible to link to those pages because they all get rendered using the one index action and controller that they're being rendered on.
I have tried setting the url from jquery using history.replacestate which works fine, however one issue remains: I do not know how to use the url:s to render a specific view on refresh or when linking to a specific view using the urls I created in replacestate. Is my approcach to dynamic loading wrong or is there a solution that can work with this current implementation?
[HttpGet]
[Route("/{controller}")]
public ActionResult Index()
{
return this.View();
}
The page argument passes in a URL that I create. Each view needs it's own URL.
function urlHistory(page) {
history.replaceState(currentState, '', page);
document.title = `${page}`;
}
I append each page to the main view and on clicking the nav bar the user can toogle between views.
function appendPage(href, page) {
$.get(href, {page: page}, function (data) {
$("#render-tables").html(data);
}).fail(function () {
$("#render-tables").empty();
});
urlHistory(page);
}
Rendering both views on the first index action(index.cshtml) that get's hit when logging in i.e the home page razor view.
<div id="render-tables"></div>
Which then in turn gets rendered using RenderBody on the Layout view.
For your requirement,I think you could store your current page in cookie or session,
I tried with partial view as below :
public IActionResult Partial(string page)
{
var formerpage=HttpContext.Session.GetString("PartialPage");
string pagename;
if (page == null&& formerpage==null)
{
pagename = "Partial1";
}
else
{
pagename = page== null ?formerpage : page;
}
HttpContext.Session.SetString("PartialPage", pagename);
return PartialView(pagename);
}
public IActionResult AnotherPartial(string anotherpage)
{
var formerpage = HttpContext.Session.GetString("AnotherPartialPage");
string pagename;
if (anotherpage == null && formerpage == null)
{
pagename = "AnotherPartial1";
}
else
{
pagename = anotherpage == null ? formerpage : anotherpage;
}
HttpContext.Session.SetString("AnotherPartialPage", pagename);
return PartialView(pagename);
}
Index page:
<button id="subBtn1" type="submit">NavBarPartial</button>
<button id="subBtn2" type="submit">Partial</button>
<br />
<button id="subBtn3" type="submit">NavBarAnotherPartial</button>
<button id="subBtn4" type="submit">AnotherPartial</button>
<div id="CrTab">
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$("#subBtn1").click(function () {
$.ajax({
url: "/Home/Partial",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn2").click(function () {
$.ajax({
url: "/Home/Partial?page=Partial2",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn3").click(function () {
$.ajax({
url: "/Home/AnotherPartial",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn4").click(function () {
$.ajax({
url: "/Home/AnotherPartial?anotherpage=AnotherPartial2",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
</script>
in View Partial1:
<a>Partial1</a>
....
The result:
I'm writing simple search engine in Lumen framework.
I have a list of status for example. The user can get one of status from the list and after click search button then in the page, I need to load data with chosen status.
One of the element is datepicker. And this datepicker work great when I refresh the page or go to the page by GET method. But I have a problem when I go on the page by POST method from my click "SEARCH". There is some code from my view where I get status from the list and pass to my controller action:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var clientId = null;
var status = null;
$("[name='deadline']").datepicker(); //there I have this error comunicat
$('#clients').on('change', function () {
clientId = $(this).val();
});
$('#statuses').on('change', function () {
status = $(this).val();
});
$('#searchForPremium').on('click', function () {
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
})
});
</script>
And there is controlelr action:
public function clientsPremium()
{
$premiumTexts = NULL;
$premiumClients = \App\Text::getPremiumClients();
$premiumTexts = \App\Text::getPremiumTexts();
$statuses = \App\Text::getStatus();
if (Request::isMethod('get')) {
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts]);
}
if (Request::isMethod('post')) {
$clientID = Request::get('client_id');
$statusName = Request::get('status');
if ($clientID != NULL) {
$premiumTexts = $premiumTexts->where('text.client_id', $clientID);
}
if ($statusName != NULL) {
$premiumTexts = $premiumTexts->where('text.status', $statusName);
}
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return response()->json(view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts])->render());
}
}
Then I have error "Uncaught TypeError: $(...).datepicker is not a function...". I cant understand how it is work and why I got this message. It appear only when I click to search button.
It is $('body').empty().html(data); or my controller action:
return response()->json(view('admin.clients-premium', ['copywriters' => $copywriters, 'statuses' => $statuses, 'positioners' => $positioners, 'clients' => $premiumClients, 'texts' => $premiumTexts, 'allowedTemplates' => $allowedTemplates, 'section' => 'clients.premium'])->render());
I tried to use $.noConflict(); but there is no effect for me. Can anyone look at my code and try to help me what should I change? I think my return "response()->json(view..." reload all page and get my jquery-ui multiple time. But I can wrong. Can anyone help me?
Reinitialize it after you change content from ajax response.
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$("[name='deadline']").datepicker();
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
After ajax success destroy the datepicker and reinitialize it as below:
$('body').empty().html(data);
$("[name='deadline']").datepicker("destroy");
$("[name='deadline']").datepicker();
you clear entire body so may be possible you include js css in body so please add and remove this div instead of entire body and if you add dynamic datepicker to any text box please use
$("[name='deadline']").datepicker(); on ajax response .
I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});
I am trying to get data from database without reloading. So I did this
Code In PasteBin
after doing that this is the ajax part for click
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
}
}
});
}
this is the ed_action.php file
$func = new functions();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ed_value = $_POST['ed_value'];
$p_authority_id = $_POST['p_authority_id'];
$user_data = array(
'ed_action' => $ed_value
);
$where_cond = array(
'where' => array('p_authority_id' => $p_authority_id),
'cross_check' => 'and',
'return_type' => 'single'
);
$table_name = 'p_authrity_user';
$update = $func->update($table_name, $user_data, $where_cond);
$ed_action_data = $func->select($table_name, $where_cond);
}
I successfully retrive the data by click. But Now I want when I click on the enable button it will show the disable button without reloading and when click on disable, it should be show the enable button. so what should I do?
Please can you help me?
As I mentioned in comments: In your success function of the ajax request you can just toggle the visibilty of the two buttons.
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
toggleButtons();
}
}
});
}
function toggleButtons(){
var enableBtn = $('button.ed_action.ed_action_enable'); // add class ed_action_enable to button so you can get it here
var disableBtn = $('button.ed_action.ed_action_disable'); // add class ed_action_disable to button so you can get it here
enableBtn.toggle(); // toggles visibility of element
disableBtn.toggle(); // toggles visibility of element
/* shorter code for this:
$('button.ed_action.ed_action_enable').toggle;
$('button.ed_action.ed_action_disable').toggle;
*/
}
For this to work you would need to
1: output both buttons into the html (disable btn hidden)
2: add one more class to the buttons so you can get them easily with jquery
I currently use this approach to obtain the correct relative URI (independent of the deployment situation). Razor code (asp.net mvc 3):
#section JavaScript
{
<script type="text/javascript">
var _getUrl = "#Url.Content("~/bla/di/bla")";
</script>
}
Separate js file:
$.ajax({
url: _getUrl,
Do you reckon there is a better approach?
Personally I prefer using HTML5 data-* attributes or including the URL as part of some DOM element that I unobtrusively AJAXify.
The thing is that you never write $.ajax calls flying around like that. You write them to correspond to some DOM events. Like for example clicking of an anchor. In this case it's trivial, you just use an HTML helper to generate this anchor:
#Html.ActionLink("click me", "someAction", "somecontroller", new { id = "123" }, new { #class = "link" })
and then:
$('.link').click(function() {
$.ajax({
url: this.href,
type: 'GET',
success: function(result) {
...
}
});
return false;
});
or maybe you are AJAXifying a form:
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
...
}
and then:
$('#myForm').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
...
}
});
return false;
});
Another example would be to use HTML5 data-* attributes when an appropriate url is not available on the corresponding DOM element. Suppose that you want to invoke a controller action with AJAX when the selection of a dropdown changes. Think for example cascading ddls.
Here's how your dropdown might look like:
#Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "myDdl", data_url = Url.Action("SomeAction") })
and then:
$('#myDdl').change(function() {
var url = $(this).data('url');
var selectedValue = $(this).val();
$.getJSON(url, { id: selectedValue }, function(result) {
...
});
});
So as you can see you don't really need this _getUrl global javascript variable that you declared in your view.
I would do the following:
Razor C# script before Javascript
#{
var myUrlString = Url.Action("ActionName", new { controller="ControllerName" });
}
JavaScript
$.ajax('#myUrlString',{
// options
});
You could also use Url.RouteUrl or Url.HttpRouteUrl.
EDIT - showing example with separated JS file
Razor
#{
var myServerGeneratedValue = Url.Action("ActionName", new{controller="ControllerName"});
}
<script type="text/javascript">
var myHelperObject = new MyHelperObject();
myHelperObject.Init('#myServerGeneratedValue');
</script>
JS file
var MyHelperObject = function(){
this.Init = function(serverGeneratedValue){
// do something with serverGeneratedValue
};
};