In my ASP.NET MVC 5 web site i have a devexpress navbar with multiple itens, each item have a single unique controller, always when i click on a item the Index action of the corresponding controller is called.
public ActionResult Index()
{
//Load large data and return it into a gridview.
}
While im loading this data i would like to show a loading panel but i dont know where i can do it using in mvc, in aspnet webforms its easier to do something like that.
Any MVC expert could help me with this?
Inside your view you suppose to use am Ajax Form, and to point to your LoadingElementId in it's definition.
Here is an example:
#using (Ajax.BeginForm("FilterNews", "News", null,
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "container", LoadingElementId = "custom-loading" }))
{
<div id='container'>
//Your helpers #Html.TextBoxFor(x => x.....) or render a partial
</div>
}
<style>
.loading{
position:absolute;
width:100%,
height:100%,
top:0,
left:0,
background:white,
}
</style>
<div id="custom-loading" class="loading">Loading..Please wait...</div>
Also if you want to display a Loader for every XHR Call u may set a binder on ajaxSend event like this :
<div id="ajax-loader-element">
<img src="#Url.Content("~/Content/Images/ajax-loader.gif")"/>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).bind("ajaxSend", function () {
jQuery('#ajax-loader-element').show();
}).bind("ajaxComplete", function() {
jQuery('#ajax-loader-element').hide();
});
});
</script>
Related
i am pretty new to asp.net core and just started developing a website with it. Recently, I encountered a problem. I have a page where there is a default dropdownlist for user to select the respective option(all the options are rendered from the selectedItem which I got from database)
However, when the user decides to add an extra dropdownlist(i use javascript to do it), the options are blank. Any suggestions?
Thank you.
function GetNewDropdown() {
return '<hr /><div class="card-body"><h4 class="card-title text-primary">Please select your options</h4 > <div class="row">' +
' <select class="form-control" asp-items="#Model.Options"></div></div>';}
Your dynamic dropdown is a tag helper. Tag helpers are server-side components. They only work when the page is initially rendered by the web server. They do not work in the browser.
What you can do is move the HTML from your JavaScript function to a partial page, and then use JavaScript to call a named page handler method that returns a PartialResult and load it into your page.
Partial:
#model List<SelectListItem>
<hr />
<div class="card-body">
<h4 class="card-title text-primary">Please select your options</h4>
<div class="row">
<select class="form-control" asp-items="#Model"></select>
</div>
</div>
Razor page:
<button id="add-dropdown">Add</button>
<div id="zone"></div>
#section scripts{
<script>
$(function(){
$('#add-dropdown').on('click', function(){
$.get('?handler=options', function(response){
$(response).appendTo('#zone');
});
});
});
</script>
}
Named handler in PageModel:
public List<SelectListItem> Options { get; set; }
public PartialViewResult OnGetOptions()
{
Options = new List<SelectListItem> {
new SelectListItem { Text = "a", Value = "1" },
new SelectListItem { Text = "b", Value = "2" },
new SelectListItem { Text = "c", Value = "3" },
};
return Partial("_DropdownPartial", Options);
}
You can read more about these things on my site:
Select tag helper:
https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper
Partial pages:
https://www.learnrazorpages.com/razor-pages/partial-pages
Named
handler methods:
https://www.learnrazorpages.com/razor-pages/handler-methods#named-handler-methods
I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.
Why Ajax.BeginForm redirect my page to new empty page after submission?
My controller code is:
[HttpPost]
public void ProductCommentAdd(int productId, string text)
{
//Do something
}
Mvc ajax call in view is:
#using (Ajax.BeginForm("ProductCommentAdd", "Shop", new AjaxOptions() { HttpMethod = "POST"}))
{
<input type="hidden" value="#Model.ProductId" name="ProductId"/>
<textarea name="text"></textarea>
<input type="submit" value="Submit"
}
When I click submit button my page redirect to new empty page. How I can fix it?
you need to include the following script to your page:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
As #Mat J and #user3206982 suggests: you probably need the unobtrusive.ajax.js file.
You can download the package from nuget and
add it in the bundles config:
bundles.Add(new ScriptBundle("~/bundles/jqueryunobtrusive").Include(
"~/Scripts/jquery.unobtrusive*"));
and in the html:
#Scripts.Render("~/bundles/jqueryunobtrusive")
Source: https://dotnetthoughts.net/mvc5-ajax-form-is-not-updating-div-but-replacing-the-whole-page-instead/
I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});
I have a pretty simple index page for an MVC project which allows you to create "jobs" and edit existing jobs. I'm trying to use an Ajax link to replace the contents of a div with the job-edit form, which the Create() and Edit() actions return as a partial view. Instead, when you click on the Ajax links, the entire page content is replaced with the partial view, instead of just the contents of the appropriate div element. Here's the relevant .cshtml code:
#{
string placeholder = "777777";
}
<body>
<ol id="JobListing">
#Html.Partial("_ExportJobListingPartial", Model)
</ol>
<br /><br /><br />
#Ajax.ActionLink("New", "Create", new AjaxOptions { UpdateTargetId = "EditJobContainer", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" })
<br /><br />
<div id="EditJobLinkContainer">
#Ajax.ActionLink("Edit", "Edit",
new { id = placeholder }, // Route values
new AjaxOptions { UpdateTargetId = "EditJobContainer", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, // Ajax options
new { id = "EditJobLink" } // Html attributes
)
</div>
<br /><br />
<div id="EditJobContainer">
EMPTY BOX HERE
</div>
<br />
</body>
</html>
<script>
$(function() {
$("#JobListing").selectable({
selected: function (event, ui) {
// Select only one at a time
$(ui.selected).addClass("ui-selected").siblings().removeClass("ui-selected");
$("#EditJobLinkContainer").html('#Ajax.ActionLink("Edit", "Edit",
new { id = placeholder }, // Route values
new AjaxOptions { UpdateTargetId = "EditJobContainer", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, // Ajax options
new { id = "EditJobLink" } // Html attributes
)');
$("#EditJobLink").click(UpdateOnClick);
}
});
$("#EditJobLink").click(UpdateOnClick);
function UpdateOnClick() {
//Get the id of the selected item
var id = $(".ui-selected").first().attr("name");
this.href = this.href.replace("#placeholder", id);
}
});
</script>
Most of the answers I've read online to similar questions suggest that maybe I'm not including the unobtrusive-ajax code correctly or in the right place. I have it in the _Layout view, before the RenderBody() call, as
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
I know this code is loading in because I inserted an alert() call into the unobtrusive-ajax.js file which launches on page load, and the links to the code in Chrome work fine. However, I had to manually replace the calls to live() with on() in the ajax scripts since live() is deprecated in the most recent version of jQuery, even though I'm pretty sure they're the latest scripts with MVC4. At one point the Ajax call was actually working for the "New" link, but I've made changes since, and nothing has been working for a few days now. Any help would be greatly appreciated.
I use empty dedicated div for that
the html is
<div id="targetDiv">
and the script is
$(".get-roles").live("click", function (e) {
$("#targetDiv").empty();
$.ajax({
url: "edit",
type: 'GET'
xhrFields: {
withCredentials: true
},
success: function (data) {
if (data) {
$("#targetDiv").append(data);
}
else {
$("#targetDiv").text("Error");
}
}
});
});
you need to include this in your page
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>