Refresh list and not page in MVC - asp.net-mvc

I have a requirement where on the left side of the page there are links and in the center, there is a table so I have to refresh the table based on the link selected however it should not refresh page, I opted for Ajax action link, however, there are issues post the implementation and I realised that is not good from design perspective so could you please help me with some solution possibly code to achieve my requirement.
#Ajax.ActionLink("click me",
"GetContacts",
"Home",
new AjaxOptions
{
UpdateTargetId = "DepartmentDetails",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnSuccess = "OnAjaxRequestSuccess"
}
)

Move the table to a partial view and load it on click of the link. This will just refresh the partial view instead of the entire master page.

You can use jQuery Ajax. It doesn’t required to refer any additional script for partial load.
Example:
#using (Html.BeginForm(new { id = "DepartmentDetails" }))
{
#Html.TextBox("deptName ");
<input type="submit" value="List Department" id="btnList" />
<div id="divDepartmentDetails"></div>
}
#section Scripts{
<script>
$("#btnList").click(function (event) {
$.ajax({
url: "#(Url.Action("Department"))",
type: "GET",
data: { deptName: $("deptName").val() },
success: function (data) {
$("#divDepartmentDetails").html(data);
}
});
});
</script>
}

Related

How to open a popup and post data to controller simultaneously using ajax call in MVC

I'm trying to implement search functionality in my Form View. The search window opens in a popup (in a partialView) and asks for search queries(figure). Now the user enters all the search fields and POST request is made and eventually popup window displays a table of search result.
Form View (which has the button to open popup window)
#Ajax.ActionLink("Search current form", "SearchAction", new { #id = "SearchBtn" }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess = "openPopup" }, new { #class ="btn btn-primary"})<br />
<div id="result" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#result").dialog({
autoOpen: false,
title: 'Search Window',
resizable:0,
width: 1000,
height: 700,
modal: true
});
});
function openPopup() {
$("#result").dialog("open");
}
</script>
SearchForm View (implemented as partial view)
#using (Html.BeginForm("SearchAction", "ViewModel", FormMethod.Post, new { #id = "searchform" }))
{
//some form elements
<div class="text-center">
<input type="submit" value="Go" class="btn btn-primary"/>
</div>
}
<div class="alert-danger">#ViewBag.emptyResult</div>
#if (Model != null)
{
//display the search results
}
Now to retain the popup I have to bind Go button to a ajax action in the same way as Form View. Also by reading this How to pass formcollection using ajax call to an action? I came to know that Ajax actions posts JSON data into the controller as opposed to key value pair which is easily accessible by FormCollection. So my question is how do I implement submit button(Ajax.Actionlink) in my search form so that it posts data into controller using FormCollection and retains the popup window as well.
Turns out I just needed to define a placeholder for the result table in my search popup.
<div id="showData" class="text-center table table-bordered bg-light"></div>
Now get your search results using Ajax call
function GetSearchResult() {
var searchParams = [];
//get search queries from textbox ids
$.ajax({
type: 'POST',
dataType: "json",
traditional: true,
data: {
s: searchParams
},
url: "/{controller name} /{action}",
success: function (result) {
var col = [];
if (isJson(result)) {
var sR = JSON.parse(result);
//create a html table using javascript and fill it which the result you got
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table); //table is what you created dynamically using javascript
}
else {
alert("No results found, Please try again");
}
}
});
}
Add this action in your controller
[HttpPost]
public JsonResult AjaxMethod(string value, string Id)
{
var updatedList = GetSearchResults(); //get search result from your repository
return Json(updatedList);
}
And as far as creating a html table thorugh javascript is concerned this helped me a lot!

Why doesn't Ajax.BeginForm execute javascript code in callback if InsertionMode is InsertBefore or InsertAfter?

When using Ajax.BeginForm, if the InsertionMode is set to Replace, when the MVC View is returning a PartialView containing some javascript code, the code is executed.
But when the InsertionMode is InsertAfter or InsertBefore, the script isn't executed.
Is it by design? Or a bug?
Here's the code :
<h2>Ajax Form Call action</h2>
#using (Ajax.BeginForm("PartialDisplay", "Test",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "PartialResult"
}))
{
<input type="submit" value="Go" />
}
<div id="PartialResult"></div>
And the code of the PartialView :
<p>Partial view</p>
<script>
alert('executed script!');
</script>
I tried with a simple ajax call, but it is working with both insertBefore and Replace (sort of 'Replace') :
function DisplayPartial() {
// call action
$.ajax({
url: '/Test/PartialDisplay',
dataType: "html", // expected response datatype
type: "POST",
success: function (data) {
$(data).insertBefore($('#PartialResult')); // insertBefore (Works)
$('#PartialResult').html(data); // sort of "Replace" (Works too)
},
error: function (xhr) {
alert('error:' + xhr.error);
}
});
}
I've done some other tries, and here's a table which shows when the js code is executed, and when it is not :
"Way to fill a div | is JS executed?
--------------------------------------------------------------
Ajax.BeginForm InsertionMode.Replace Yes
Ajax.BeginForm InsertionMode.InsertAfter No
Ajax.BeginForm InsertionMode.InsertBefore No
jQuery .insertBefore Yes
jQuery .insertAfter Yes
jQuery .prepend Yes
jQuery .append Yes
jQuery .html (replace) Yes
Vanilla JS .innerHTML No
Vanilla JS .outerHTML No

My asp.net MVC partial view is unresponsive after initial ajax call?

I am working on an asp.net mvc 4 application and I am using a PartialView for a table in the Index view. After I make the initial ajax call the request is successful and the UI is updated accordingly. But when I try to update again, the JavaScript is unresponsive for the click event.
Is this typical?
AJAX call:
$("#button").click(function(){
$.ajax({
url: 'url',
type: "POST",
data: $("#form0").serialize()
}).done(function (allData) {
$("#mypartialId").html(allData);
ResizeContent();
}).fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Something like this is in my controller Index action:
if(Request.IsAjaxRequest())
{
return PartialView("_PartialView", model);
}
return View(model);
Razor Ajax.BeginForm, has id of form0 by default:
#using (Ajax.BeginForm("Index", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "mypartialId"
}))
My partial rendering in Index:
<div id="mypartialId">
#{Html.RenderPartial("_PartialView", Model);}
</div>
This works once but when I click the button switch is in the partialView the JavaScript becomes unresponsive. I am guess its something with the Index view not reloading with the partialView...would there be any way around that?
I used .on() function instead of just the .click() as #Sergey Akopov suggested. After that I had another problem after that because the data coming back was a table, so IE9 was giving me UI problems.
The fix was to remove the white space from the table tags like so, before injecting it into the DOM
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
table = table.replace(expr, '><');
$("#mypartialId").html(table);
Here is a link to the 'td' issue displaying weird in IE9.

Replace the Ajax.ActionLink by the same functionality with jQuery

With asp.net mvc we can do an ajax call like this:
#{
var ajaxOpts = new AjaxOptions { UpdateTargetId = "main-content", OnBegin = "fctTabLoading", OnComplete = "fctTabLoaded", InsertionMode = InsertionMode.Replace };
}
#Ajax.ActionLink("my link text", "MyAction", "MyController", new { id = Model.RequestID }, ajaxOpts)
Which produce the following html:
<a data-ajax="true" data-ajax-begin="fctTabLoading" data-ajax-complete="fctTabLoaded" data-ajax-mode="replace" data-ajax-update="#main-content" href="/MyController/MyAction/19">my link text</a>
Now I would like to execute the same ajax call but from jQuery and I don't know how to proceed!
I would like something like:
$.ajax({
type: "Post",
url: myURL,
begin: fctTabLoading,
complete: fctTabLoaded,
mode: "replace",
update: "#main-content",
cache: false,
success: function () { alert('success'); }
});
I know the above ajax script won't work because 'mode' and 'update' are not recognized. So I am blocked.
It drives me crazy :(
Why I cannot use the MVC ActionLink? Because I first need to show a jquery dialog to let the user confirm then only do the ajax call in order to refresh a specific div on my page.
Any help is greatly appreciated.
Thanks.
You could start by replacing your Ajax link with a normal link:
#Html.ActionLink(
"my link text", // linkText
"MyAction", // actionName
"MyController", // controllerName
new { id = Model.RequestID }, // routeValues
new { id = "mylink" } // htmlAttributes
)
which will produce the following markup:
my link text
and then in a separate js file unobtrusively AJAXify it:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
type: 'POST',
beforeSend: fctTabLoading, // corresponds to your OnBegin callback
complete: fctTabLoaded, // corresponds to your OnComplete callback
success: function(result) {
$('#main-content').html(result);
}
});
return false;
});
});
As you know, the Ajax.ActionLink uses jquery.unobtrusive-ajax.js to execute the ajax links.
If you look at that file, you will see that the event handlers use jquery's live event binder. This binds the event listener to the document object. So, if you wanted to confirm before this event was triggered, you could bind directly to the element like the following:
$('#YOUR_ELEMENT').click(function () {
var confirmed = confirm("CONFIRM_MESSAGE");
if (!confirmed ) {
return false;
}
return true;
});
To use jquery dialog you could do the following:
function confirmDialog () {
$('#YOUR_DIALOG').dialog(
{ buttons: { "Ok": function() { return true; },
{ "Cancel": function() {return false;}
}
});
}
and then you would set confirmed in the previous function to confirmDialog().
***The dialog options may not be exactly what you want, but this should get you going.

Is not the way I want PartialViewResult

I try something.I apologize in advance for my english.
My Action code;
public PartialViewResult showProduct()
{
var query = db.Categories.Where((c) => c.CategoryID == 4);
return PartialView("_EditCategory",query);
}
My view code:
#using (Ajax.BeginForm(
"showProduct",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "result"
}))
{
<input type="submit" value="Get" />
}
<div id="result">
</div>
When i pushed the submit button ( which value is get) the results return but in another page like http://localhost:57616/Home/showProduct but i want return to result div in index page.
Any one can help me?
So, how I handled this myself was something like this:
$(document).ready(function () {
var options = {
target: "#mytargetdiv",
url: '#Url.Action("Edit", "IceCream")',
};
$("#editIceCreamForm").submit(function () {
$(this).ajaxSubmit(options);
return false;
}
// other stuff
});
in other places, where I wanted to do in-place editing of things I'd do something like this:
<input type="button" id="someid" value="Edit" data-someid="#Model.SomeId"/>
and then some ajax like so:
$(function () {
$("#someid".click(function () {
var theId = $(this).data('someid');
$.ajax({
type: "GET",
data: "id=" + theId,
url: '#Url.Action("Edit", "Something")',
dataType: "html",
success: function (result) {
$('#targetdiv').html(result);
}
});
});
});
So, if you're not interested in using jQuery and want to use the MS Ajax stuff, are you including the MicrosoftAjax.js and MicrosoftMvcAjax.js files on the page? If you don't have those, I believe what will happen is it just does the default (non-Ajax) submit.

Resources