Thanks in advance.
I am working on a product filter view similar to some thing like on amazon. where I have refresh multiple views but the data for all the partial view come from single ajax call how to refresh multiple partial view. I can refresh main content area completely but some partial views are not supposed to be refreshed.
I broke it down into steps so you can follow/modify and add your partials like here. First, add 3 Partial Views, they have the same code like below,
#model int
<div class="container fluid">
<h1>PartialDemo#(Model)</h1>
<h3>The views will all update when you click update button below</h3>
</div>
DashboardWidgets.cshtml, the code like below, whatever your csthml page is
//<div class="row-fluid">
// <div class="col">
<div id="WidgetID_1" class="container">
#Html.Partial("_PartialWidget1", 1)
</div>
<div id="WidgetID_2" class="container">
#Html.Partial("_PartialWidget2", 2)
</div>
<div id="WidgetID_3" class="container">
#Html.Partial("_PartialWidget3", 3)
</div>
<div id="WidgetID_4" class="container">
#Html.Partial("_PartialWidget3", 4)
</div>
//</div> // the col
//</div> // the row
// lcik below button to update the partials above
// ***** One button will update them all like you wanted
<button type="button" onclick="UpdateMyWidgets()" class="btn btn-primary">Update All Partial View Views</button>
#section scripts{
<script type="text/javascript">
// this one button will update all your partials/widgets, you can add more partials in this function and just copy paste.
function UpdateMyWidgets() {
$.ajax({
url: "#Url.Action("Widget1")", // whom to call
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_1").html(data); // tell it which div to append on return
}
})
$.ajax({
url: "#Url.Action("Widget2")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_2").html(data);
}
});
$.ajax({
url: "#Url.Action("Widget3")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_3").html(data);
}
});
}
</script>
}
When click the "Update All Partial View Views" button, it will call "Update" method. If success, the return data will replace div's content
Backend action ajax request.
// these actions get called from the Update Buttons
public ActionResult Widget1()
{
return PartialView("_PartialWidget1", 11);
}
public ActionResult Widget2()
{
return PartialView("_PartialWidget2", 21);
}
public ActionResult Widget3()
{
return PartialView("_PartialWidget3", 31);
}
Related
I have a view with a button, when click this button, an ajax function calls controller method ApplicationAndUse which is supposed to pass a list to a partial view included in my view. The partial view content is supposed to be refreshed, but this doesn't work, my partial is still empty.
My code :
Main view :
#model List<String>
<div class="row">
<div class="col-md-2">
#foreach (var item in Model)
{
<div id="univers-#item" class="btn btn-info">#item</div><br />
}
</div>
<div class="col-md-10">
#Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(function () {
$('[id^=univers]').click(function () {
var selectedButton = $(this).attr('id');
var selectedUniverse = selectedButton.substring(selectedButton.indexOf('-') + 1, selectedButton.lenght);
$.ajax({
url: "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse",
type: "POST",
data: { idUniverse: selectedUniverse },
dataType: "json",
});
});
});
</script>
}
Partial view :
#model List<int>
#if (Model!= null) {
foreach (var item in Model)
{
<div id="ApplicationUse-#item" class="btn btn-default">#item</div><br />
}
}
Controller function :
[OutputCache(Duration = 0)]
public ActionResult ApplicationAndUse(String idUniverse)
{
List<int> items = new List<int>();
items.Add(1);
items.Add(2);
return PartialView("_ApplicationAndUsePartial", (object)items);
}
what do i miss?
Give a unique Id to the div where we want to show the partial view content.
<div id="myPartial" class="col-md-10">
#Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
And in the success handler of the ajax method, update this div's innerHTML with the response coming from the ajax call. Also you do not need to pass specify the dataType value when making the ajax call.
var myUrl= "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse";
$.ajax({ type: "POST",
url : myUrl,
data: { idUniverse: selectedUniverse },
success:function(result){
$("myPartial").html(result);
}
});
Always you should use the Url.Action or Url.RouteUrl html helper methods to build the url to the action methods. It will take care of correctly building the url regardless of your current page/path.
var myUrl= "#Url.Action("ApplicationAndUse","UseAndNeeed")";
This works if your js code is inside the razor view. But If your code is inside a seperate javascript file, you may build the url(s) in your razor view using the above helper methods and keep that in a variable which your external js file code can access. Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
#section Scripts
{
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
}
And in your PageSpecificExternalJsFile.js file, you can read it like.
var myUrl= myApp.Urls.baseUrl+"UseAndNeed/ApplicationAndUse";
$("#myPartial").load(myUrl+'?idUniverse=someValue');
In MVC 4, I have a textbox with Autocomplete functionality in a partial view And i am using this partial view in two views,view 1 and View 2.In View 1 ,it is working fine, as view 1 does not have any postback, while in View 2, i have a submit button causing postback,and after this postback,the partial is shown on the screen or else it is hidden.The Autocomplete here is not working.
$("#txtProduct").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
data: { term: request.term },
datatype: JSON,
url: 'UploadEligibilityCodes/GetAllMatchingProducts',
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value.ProductName.concat("(", value.ProductId, ")"),
value: value.ProductName,
pid: value.ProductId
};
}))
}
});
},
select: function (event, ui) {
$('#hdnProductIdSearch').val(ui.item.pid);
}
});
This is the code of my text box defined in Partial view named SearchFilters.cshtml and View 2 which uses this partial view as follows.
#using (Html.BeginForm( "Validate","UploadEligibilityCodes",FormMethod.Post, new {id="UploadForm" , enctype = "multipart/form-data" }))
{
<div class="col-sm-1 form-group">
<button type="submit" class="SIMPLDocumentUploadSave" id="importbtn" value="Import" style="width: 100px"> Import</button>
</div>
}
<div class="col-sm-12 form-group SIMPLAdvancedFilterOptions">
#Html.Partial("SearchFilters")
</div>
I saw some examples using Sys.WebForms.PageRequestManager in ASP.Net, but the same i am not able to apply it html of mvc application.Please help :)
Can you replace your submit button with regular one and call submit() on form manually with jQuery? This can help you with postback issue
I have a MVC 4 project where I want to call a controller from view A and than append the returned view B in view A.
something like that:
view A (aspx):
<script type="text/javascript">
function HeadBtn_Click() {
/////
var url = 'IVR/';
window.location.href = url;
////this works, but I want to stay in view A
//// example of what I want:
divContant.innerHTML = ////The returned view here////
}
</script>
<body>
<input type="image" onclick="HeadBtn_Click();" src="../../Images/buttonHodaot.png">
<div id="divContant"> ////Append Here//// </div>
</body>
view B(aspx):
////I will have alot more to append, but just for now:
<div>
<p>To Append</p>
</div>
thanks
Another approach (if you really want to render the view B after view A loads)..
Make use of AJAX and get the response HTML of view B, then append it to divContent div. Like this,
<script type="text/javascript">
function HeadBtn_Click() {
$.ajax({
type: 'GET',
url: url,
dataType: 'HTML',
success: function(data) {
$('#divContant').html(data);
}
});
}
</script>
Hope it helps, thanks.
You can use RenderAction and return viewB as partial view
<div id="divContant">
#{Html.RenderAction("controllerName","actionName");}
</div>
http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html
I have a webpage where many section of the page gets loaded using jQueryAjax after intial load. Now I need to download the web page completey using C#. It should be downloaded once all the ajax call completes.
I tried many ways to do that but didnot get through. Can sombody suggest the best way to handle that?
I have my MVC view like this
#{
ViewBag.Title = "My Page";
}
<div id="Banner" class="divMain" style="height: 92px;" style="margin-left: 0.3em">
</div>
<div style="float:left; width:99.6%">
<div id="StockPriceCharts" class="div_Chart" style="margin-top:0.1em;margin-left:-0.1em">
</div>
<div id="Rating" class="divMain_48" style="margin-left: 0.3em; min-height:140px">
<div class="ControlHeader">
Entity Details</div>
<div id="dvEntity" >
</div>
</div>
<div id="FilMeetings" class="divMain_48" style="float:left;">
<div class="ControlHeader">
MEETINGS
</div>
<div id="dvMeeting" style="height: 119px;" class="loading">
</div>
</div>
</div>
<span>
<input id="IdHidden" type="hidden" value="#ViewBag.SymbolId"/>
</span>
<script type="text/javascript">
$.ajaxSetup({ cache: false });
// For Entity Detail
$.ajax({
url: '/HomePage/Entity Detail/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvEntity').html(result);
})
.error(function (xhr, status) {
$('#dvEntity').html('<div style="height:40px;" class="loading">Failed to load Entities</div>');
});
$.ajax({
url: '/HomePage/GetMEETINGSs/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvMeeting').html(result);
})
.error(function (xhr, status) {
$('#dvMeeting').html('<div style="height:40px;" class="loading">Failed to load Business description</div>');
});
</script>
I have removed some part and put dummy value for brevity. But I have similar more section that are getting loaded via AJAX and there are some static content as well. When I download it ajax section is not getting loaded.
If I understand you right, after page loaded you're loading data with ajax and rendering it with JavaScript.
If so, you have to implement data rendering in Razor way (If you're using ASP.NET MVC). Each section should have own partial view. Create a new View and put Partials in it.
public ViewResult Index()
{
var api = new YouWebApiController();
var sectionData_1 = api.GetSectionData_1();
var sectionData_2 = api.GetSectionData_2();
var sectionData_3 = api.GetSectionData_3();
ViewBag.SectionData_1 = sectionData_1;
ViewBag.SectionData_2 = sectionData_2;
ViewBag.SectionData_3 = sectionData_3;
return new View();
}
In your view:
<body>
#Html.RenderPartial("SectionPartial_1", ViewBag.SectionData_1);
#Html.RenderPartial("SectionPartial_2", ViewBag.SectionData_2);
#Html.RenderPartial("SectionPartial_3", ViewBag.SectionData_3);
</body>
#{
var db = Database.Open("CMS");
//retrieving the username of the user from the session
var session_username = Session["session_username"];
//get the details of the user from the database
var getuserdetailscommand = "SELECT * from student where student_username = #0";
var getuserdetailsdata = db.Query(getuserdetailscommand, session_username);
var statusfirstname = "";
var statuslastname = "";
var statusavatar = "";
foreach(var row in getuserdetailsdata){
statusfirstname = row.student_firstname;
statuslastname = row.student_lastname;
statusavatar = row.student_avatar;
}
//on submit execute the following queries
if(IsPost){
if(Request["button"] == "sharestatus"){
//retrieve the data from the form input fields
var statusbody = Request.Form["statusbody"];
var statususername = session_username;
//insert the status for the username into the database
var insertcommand = "INSERT into status(status_body, status_date, status_username, status_firstname, status_lastname, status_avatar) VALUES (#0, #1, #2, #3, #4, #5)";
db.Execute(insertcommand, statusbody, DateTime.Now, session_username, statusfirstname, statuslastname, statusavatar);
}
}
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function get() {
$.post('statusupdateform.cshtml', { name: form.name.value }
}
</script>
<form class="status-form" role="form" action="" enctype="multipart/form-data" method="post" name="form">
<div class="form-body">
<div class="form-group">
<textarea class="form-control" placeholder="What's on your mind?" name="statusbody"></textarea>
</div>
</div>
<div class="form-footer">
<div class="pull-right actions">
<button class="btn btn-primary" name="button" value="sharestatus" onclick="event.preventDefault();get();return false;">Share</button>
</div>
</div>
</form>
This is the code in my cshtml file. I want to submit the form using ajax so that the whole page doesn't get refreshed everytime a user submits anything.
The C# code necessary to run the form is also provided in the code.
Any help how can I submit the for using ajax?
Thank you!
Use Javascript or JQuery for this.
E.g. add script tag with link to jquery code file and then use $.get or $.post to make ajax call.
You should remove
method="post"
From the form as this will make the full page submit. Also you can find more information on how to do this in the Jquery documentation.
See the bottom of this link for an example:
http://api.jquery.com/jquery.post/
Use This to perform your operations
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});