There is a Layout page in my MVC app and with the help of a menü link on this Layout page, I render a PartialView having only 5-6 input with no css or js import. As it can bee seen on the image below, it takes approximately 4 second just loading this PartialView and I think there is a big mistake regarding to this logic. Could you please have a look at the page and clarify me about where I did mistake?
Note: As far as I see the time consuming part of the AJAx method is in the success part (until $("#div-page-content").html(''); line). Is it needed or how can I change that part with a faster code block?
LayoutPage:
<a href="#" id="register" class="nav-link" onclick="renderPartial(event, 'Account', 'Create')">
<div id="div-page-content" class="page-content">
#RenderBody()
</div>
<script>
function renderPartial(e, controller, action) {
e.preventDefault();
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#div-page-content").html('');
$("#div-page-content").append(data);
},
error: function (data) { onError(data); }
});
};
</script>
_PartialView:
<div>
//... code omitted fr borevity (there is no js or css import in this view
</div>
Controller:
[HttpPost]
public ActionResult Create()
{
return PartialView("_Register");
}
Related
After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.
I'm making some changes on my perl website (file manager)
I want to make pages to load faster and to have a nicer use of pages especially for files page hen content will be loaded with ajax everytime it's requested .
I have paging which works perfectly via ajax but when i want to do this after i click a button it doesnt work just gives me an OK text for response, below are codes I'm using for paging
function setPagination(element, opts)
{
$(element).paging(opts.total,
{
format: '< ncnn (- p) >',
perpage: opts.perpage,
onSelect: function (page)
{
if(document.readyState !== 'complete') return;
$.ajax({
url: opts.url,
type: 'POST',
data:
{
op: opts.op,
load: opts.load,
page: page.toString(),
fld_id: opts.fld_id,
usr_login: opts.usr_login
},
success: function(result)
{
$(opts.target).html(result);
if(typeof addthis !== 'undefined') { addthis.layers.refresh(); }
}
});
},
onFormat: function (type)
{
var show_right = this.pages > 4;
var show_block = !show_right || this.value != this.pages;
if(this.pages <= 1) return ' ';
/* TODO: looks ugly, needs refactoring */
switch (type)
{
case 'right':
if(!show_right) return '';
return show_right
? '<a>' + this.value + '</a>'
: '';
case 'block':
if(!show_block) return '';
return this.value == this.page
? '<span>' + this.value + '</span>'
: '<a>' + this.value + '</a>';
case 'next': // >
return 'Next';
case 'prev': // <
return 'Prev'
case 'fill':
return show_right ? ".." : '';
}
}
});
$(element).css('cursor', 'pointer');
}
html code with perl
<div class="files">
<div id="files_g">
<TMPL_INCLUDE files_grid.html>
</div>
<div class="grid paging bottom"></div>
</div>
setPagination('.files .grid',
{
op: 'my_files',
total: '<TMPL_VAR files_total>',
load: 'files_grid',
target: '#files_g',
perpage: '<TMPL_VAR per_page>',
fld_id: '<TMPL_VAR folder_id>',
});
That's the paging page which i use to load the file content only not the entire page and it work perfectly .
Now I want to select a file and after clicking to set an custom options for the that file i have select after this i want the file content to reload here is where i cant find out why is'nt working
below are codes that i want to use
function setFileFlag(file_ids, name, value) {
$.ajax({
type: 'POST',
url: '?',
data: {
op: 'my_files',
set_flag: name,
load: 'files_grid',
value: value,
file_id: file_ids,
},
success: function(result) {
$('#files_g').html(result);
if(typeof addthis !== 'undefined') { addthis.layers.refresh(); }
},
});
}
$('.flag').click(function() {
var name = this.name.replace(/(un)?set_/,'');
var value = this.name.match(/^set_/) ? 1 : 0;
var file_ids = $('[name=F1] [name=file_id]')
.filter(function() { return this.value != 0 && this.checked; })
.map(function() { return(parseInt(this.value)) })
.toArray();
setFileFlag(file_ids, name, value);
});
Hello I have html text in this html text there are two img(there may be more than 2 img) I want to take this img's src and change it. Change operation will be in server side so.
In js I wrote
$(content).find('img').each(function () {
var src = $(this).attr('src');
if (src !== "" || src != null)
//var result = content.replace(src, changeImageUrls(src));
});
content is html string. With this code I find src of img but after this I will send it to controller.
function changeImageUrls(urls) {
console.log(urls);
var newurl = "";
$.ajax({
type: 'POST',
url: '#Url.Action("Upload", "Media")',
data: JSON.stringify({
url: urls
}),
async: false,
success: function (data) {
if (data.Status !== 200) {
toastr.warning('#Resources.Resource.Error_Unexpected');
return;
}
if (data.Result === "FILE_COULDNT_SAVED") {
toastr.warning('Sayfa tasarımı kaydedilemedi.');
return;
}
newurl = data.Result;
console.log("Yeni url verildi");
},
error: function (error) {
toastr.warning('#Resources.Resource.Error_Unexpected');
return;
}
});
return newurl;
}
I wrote this function two post data to controller.
[HttpPost]
public ActionResult Upload(string url)
{
if (string.IsNullOrEmpty(url))
return Content(Serialization.JsonSerialize(new { Status = 400 }));
return Content(Serialization.JsonSerialize(new { Status = 200, Result = MediaRepository.Upload(url) }));
}
When I post to controller , controller get url always null.I couldn't find the problem. Thanks in advance
I got a link that renders partial view using AJAX.
Here is my link code:
<a href="#" onclick="LoadChildCategories(#i.CategoryId,
#i.IsTrading.ToString().ToLower())">#i.Name</a>
And here is LoadChildCategories function code:
function LoadChildCategories(id, isTrading) {
var link;
if (isTrading === false) {
link = '#Html.Raw(#Url.Action("NonTradingCategories", "Home",
new {categoryId = -1}))';
} else {
link = '#Html.Raw(#Url.Action("ModelList", "Home", new {categoryId = -1}))';
}
link = link.replace("-1", id);
$.ajax({
url: link,
method: 'GET',
success: function(data) {
$("#viewPartial").html(data);
}
});
}
When I click it without CTRL it's ok, partial view renders into my div. But when I click it with CTRL partial view renders into current tab and then another tab opens at Index page.
And when I rightclick on link and select to open it in another tab then nothing happens at current tab and new tab opens at Index page.
So, is there any ways to handle that?
I found pretty nice solution, so I modified project according to this solution: Make an MVC Application into a SPA with AJAX and History.js
1) Make controller methods return View, not PartialView and add one line of code than will check is it an AJAX request:
public ViewResult Category(int id)
{
ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
var node = CategoriesHandler.Instance.First(x => x.CategoryId == id);
var childCategories = CategoriesHandler.Instance.Where(x => x.ParentId == node.Id).ToList();
ViewBag.Message = node.Name;
return View(childCategories);
}
2) Edit _ViewStart.cshtml like that:
#{
Layout = ViewContext.ViewBag.IsAjaxRequest == true ? null : "~/Views/Shared/_Layout.cshtml";
}
3) Prepare links to be managed via AJAX:
#i.Name
4) Create container for views at _Layout.cshtml
#/*Some layout stuff*/
<div id="bodyContent">
#RenderBody()
</div>
#/*Other layout stuff*/
5) Prepare helper javascript file like that:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
function navigateToURL(url) {
$('#bodyContent').html('<div class="loader"> </div>');
$.ajax({
type: "GET",
url: url,
dataType: "html",
cache: false,
success: function (data, status, xhr) {
$('#bodyContent').hide();
contentShell.html(data);
$('#bodyContent').fadeIn(500);
},
error: function (xhr, status, error) {
$('#bodyContent').hide();
alert("TEST_Error");
}
});
}
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
if (State.url === '') {
return;
}
navigateToURL(State.url);
});});
6) Do not forget to include your javascript files into the bundle!
Javascript Code:
<script type="text/javascript">
function MusteriBilgileriKaydet2() {
var veri = {
AnaOzelDurumId: AnaOzelDurumId.GetValue(),
AnaİlgiliPersonelId: AnaİlgiliPersonelId.GetValue(),
};
if (veri.MusteriAdiTextBox1.trim() == "" || veri.MusteriAdiTextBox1 == undefined || veri.MusteriAdiTextBox1 == null) {
$("#showwarning222").html('<img src="/Image/warning.png" title="Müşteri Adı Giriniz!">').show();
}
else {
LoadingPanel.Show();
$.ajax({
url: "/Home/GenelMusterilerGridView2",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) { // Error
LoadingPanel.Hide();
alert("Müşteri Adı Mevcut");
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
else { // Success
$("#MusterilerGetir").html(mydata);
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
},
error: function () {
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
});
return false;
}
}
</script>
My Controller:
public ActionResult GenelMusterilerGridView2(MyModel model)
{
var stringView = RenderRazorViewToString("MerkezPartial", ModelleriGetir());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { error6 = true, JsonRequestBehavior.AllowGet });
}
}
return null;
}
My all codes works well .
I only want to open in new tab page .
So
How can i open in new tab in browser after i post data to my controller ?
Any help will be greatly appreciated.
Thanks.
you can add to your html <a href tag a target that looks like this.
Link name or text
OR you can in your javascript code add
function OpenNewTab(url){
var something = window.open(url, '_blank');
something.focus();
}
Now this should be working fine but just because some clients prevent pop-ups then you could add this to your html tag too.
<div onClick="OpenNewTab();">your link name</div>
Hope this will work for you
Cheers!