Show different web pages in multi view using link button - asp.net-mvc

I have developed a web site on ASp.net 3.5 with VB which have multiple pages the problem is i want to show all pages in one view user click on link button and coprresponding page should open on single page then user click to other link button and another page open in same browser window with same layout.Please suggest me what should i do?

You could use AJAX to achieve this. So for example let's suppose that you have multiple controller actions that return partial views. You could then create links on your page to those actions:
<%= Html.ActionLink("page 1", "Page1", "SomeController", null, new { id = "link1" }) %>
<%= Html.ActionLink("page 2", "Page2", "SomeController", null, new { id = "link2" }) %>
<%= Html.ActionLink("page 3", "Page3", "SomeController", null, new { id = "link3" }) %>
and 3 corresponding placeholders where the pages would be loaded:
<div id="page1" />
<div id="page1" />
<div id="page1" />
you could now AJAXify those links in a separate javascript file. Example with jquery:
$(function() {
$('#link1').click(function() {
$('#page1').load(this.href);
return false;
});
$('#link2').click(function() {
$('#page2').load(this.href);
return false;
});
$('#link3').click(function() {
$('#page3').load(this.href);
return false;
});
});
I would also strongly recommend you going through the tutorials on the ASP.NET MVC site.

Related

Ajax.ActionLink alternative with mvc core

In MVC5 there is #Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.
I have tried using #Html.ActionLink like the following but it doesn't update the form, it return just the partial view:
View:
#Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
{
data_ajax = "true",
data_ajax_method = "GET",
data_ajax_mode = "replace",
data_ajax_update = "environment-container",
#class = "btn btn-danger"
})
control:
public async Task<ActionResult> GetEnvironment(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return PartialView("_Environment",environments);
}
Partial view:
#model PowerPhysics.Models.Environments
this is a partial view
Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):
View:
#Component.InvokeAsync("Environments", new { id = Model.Id }).Result
component:
public class EnvironmentsViewComponent : ViewComponent
{
public EnvironmentsViewComponent(PowerPhysics_DataContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return View(environments);
}
}
How can I update just a part of a view by using PartialViews in MVC6?
You can use a tag as follows:
<a data-ajax="true"
data-ajax-loading="#loading"
data-ajax-mode="replace"
data-ajax-update="#editBid"
href='#Url.Action("_EditBid", "Bids", new { bidId = Model.BidId, bidType = Model.BidTypeName })'
class="TopIcons">Link
</a>
Make sure you have in your _Layout.cshtml page the following script tag at the end of the body tag:
<script src="~/lib/jquery/jquery.unobtrusive-ajax/jquery.unobtrusive-ajax.js"></script>
ViewComponent's are not replacement of ajaxified links. It works more like Html.Action calls to include child actions to your pages (Ex : Loading a menu bar). This will be executed when razor executes the page for the view.
As of this writing, there is no official support for ajax action link alternative in aspnet core.
But the good thing is that, we can do the ajaxified stuff with very little jQuery/javascript code. You can do this with the existing Anchor tag helper
<a asp-action="GetEnvironment" asp-route-id="#Model.Id" asp-controller="Environments"
data-target="environment-container" id="aUpdate">Update</a>
<div id="environment-container"></div>
In the javascript code, just listen to the link click and make the call and update the DOM.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
var _this=$(this);
$.get(_this.attr("href"),function(res){
$('#'+_this.data("target")).html(res);
});
});
});
Since you are passing the parameter in querystring, you can use the jQuery load method as well.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
I add ajax options for Anchor TagHelper in ASP.NET MVC Core
you can see complete sample in github link :
https://github.com/NevitFeridi/AJAX-TagHelper-For-ASP.NET-Core-MVC
after using this new tagHelper you can use ajax option in anchor very easy as shown below:
<a asp-action="create" asp-controller="sitemenu" asp-area="admin"
asp-ajax="true"
asp-ajax-method="get"
asp-ajax-mode="replace"
asp-ajax-loading="ajaxloading"
asp-ajax-update="modalContent"
asp-ajax-onBegin="showModal()"
asp-ajax-onComplete=""
class="btn btn-success btn-icon-split">
<span class="icon text-white-50"><i class="fas fa-plus"></i></span>
<span class="text"> Add Menu </span>
</a>
Use tag helpers instead and make sure to include _ViewImport in your views folder.
Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.
Example - Razor Page
<script type="text/javascript" language="javascript">
$(function () {
var myEl = document.getElementsByName('theName');
$(myEl).click(function (e) {
e.preventDefault();
var _this = $(this);
$.get(_this.attr("href"), function (res) {
$('#' + _this.data("target")).html(res);
});
});
});
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>
<div id="divReplacable">
Some Default Content
</div>

redirect to action asp.net MVC

I want to redirect to an action afer the execution of create method
so the create method returns this:
return Json(new
{
Data = base.RenderView("_Forme ", model),
Message = (string)TempData[TEMP_DATA_MESSAGE_KEY],
Result = (AjaxResultType)TempData[TEMP_DATA_CODE_KEY]
}, JsonRequestBehavior.AllowGet);
}
Layout page:
<div> #Html.Partial("_Forme") </div>
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
**In the View: _Forme.cshtml **
<a href="#Url.Action("Create", "Uneform")"
#if (Model.nouveau==true)
{ Create}
{ Update }
</a>
I want to be able to refrech the layout page and display all the partial views.
I already try redirect to action using javascript didn't work,any help
If you want to refresh only some part of the layout page, wrap that in a container div and make an ajax call to get the new markup for this area
<div id="updatable">
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
</div>
and in your ajax call's success event, you may use the $.load method
$("#updatable").load("/Home/GetUpdatedHeader");
Assuming GetUpdatedHeader action method return a partial view which has the other 2 partials in it.
If you simply want to reload the same page, you can do this in javascript.
window.location.href = window.location.href;
You can do this is in your ajax call's success event.
If you want to redirect to another action/page
window.location.href ="/Home/Index"; //Replace this value with your url
You may also send the url for your new page in the json response(You can use the UrlHelper to build the urls) and use that for the redirect.

Display view result in a div in ASP.NET MVC

I have this :
<div>#Html.ActionLink("MyLink", "Index", "Home")</div>
<div id="ToDisplayResult></div>
Is it possible to display the View or PartialView returned by the controller in a specific div ?
Thanks,
If you add this:
<div id="ToDisplayResult>#Html.Action("MyActionThatReturnsPartial", "Home")</div>
It will display the partial view result where you desire. Make sure that your controller returns a partial view result, of course.
<div>#Html.ActionLink("MyLink", "Index", "Home", null, new { id = "mylink" })</div>
<div id="ToDisplayResult></div>
and in a separate javascript file AJAXify:
$(function() {
$('#mylink').click(function() {
$('#ToDisplayResult').load(this.href);
return false;
});
});
And for completeness of my answer (not that this is something I would recommend) you could use the Ajax helpers:
<div>
#Ajax.ActionLink(
"MyLink",
"Index",
"Home",
new AjaxOptions { UpdateTargetId = "ToDisplayResult" }
)
</div>
<div id="ToDisplayResult></div>
Just make sure you have included the proper unobtrusive script to your page in this case:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
the most basic way of updating a div would be using jQuery .load
$('#ToDisplayResult').load('/SomeController/Action');
see this question for more details:
How can I reload a div with a PartialView in ASP.NET MVC using jQuery?

Can we dynamically change the URL with Ajaxy call on ASP.NET MVC page?

I have an ASP.NET MVC application that has a view called Products.
This Products View has a Left Menu Navigation that is implemented using NavMenuProducts.ascx Partial View.
This Menu is implemented using JQuery Treeview so that it has the list of ProductNames as the Parent Node and it is expandable(For Example: 10 Products).
Each of these Products have a ChildNode as DocTypeName and it is a hyperlink(For Example: 3 DocTypeNames).
When the user clicks ChildNode Hyperlink all the matching Documents are displayed and is implemented using Ajaxy call. So that the user has better UI experience.
But the problem with this is the url always is static(Example: http://DocShare )
But based on the Node that is clicked, I want the url like http://DocShare/Products/Product1/Letter
I am wondering how to make this dynamic url using Ajaxy call.
NOTE: If I am using HTML.ActionLINK, then I am getting dynamic URL. But this ActionLink, while the Page is loading, we are getting random treeview screen. TO avoid that flickering tree effect, I am making Ajax call for better UI experience.
Any solution would be appreciated for getting dynamic url with Ajaxy call.
Here is the Code:
NavigationProducts.ascx Page:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MedInfoDS.Controllers.ProductViewModel>" %>
<script type="text/javascript">
$(document).ready(function () {
$(".docId").click(function () {
alert("DocTypeName: " + this.id);
$("#docDetails").load('<%= Url.Action("DocumentDetails") %>', { ProductName: "darbepoetin alfa", DocTypeName: this.id }, function (responseText, status) {
});
return false;
});
});
<div id="treecontrol">
<a title="Collapse the entire tree below" href="#">Collapse All</a> | <a title="Expand the entire tree below"
href="#">Expand All</a> | <a title="Toggle the tree below, opening closed branches, closing open branches"
href="#">Toggle All</a>
</div>
<div id="divByProduct">
<ul id="red" class="treeview-red">
<% foreach (var item in Model.Products)
{ %>
<li><span>
<%=item.Name%></span>
<ul>
<%foreach (var item1 in Model.DocTypes) { %>
<li><span>
<%= Html.ActionLink(item1.DocTypeName, "Products", new { ProductName = item.Name, DocTypeName = item1.DocTypeName })%>
<br />
<a class="docId" href="#" id="<%=item1.DocTypeName%>"><%= item1.DocTypeName%></a>
<%= Html.Hidden("ProductName", item.Name)%>
</span></li>
<% } %>
</ul>
</li>
<% } %>
</ul>
</div>
Controller Method:
// Response to AJAXy call to populate details for given ProductName and DocType
[HttpPost]
public virtual ActionResult DocumentDetails(string ProductName, string DocTypeName)
{
var entities = new MIDSContainer();
if (ProductName == null) return View();
int ProductId = (entities.Products.FirstOrDefault(p => p.Name == ProductName)).ProductId;
int DocTypeId = (entities.DocTypes.FirstOrDefault(d => d.DocTypeName == DocTypeName)).DocTypeId;
var documents = (from d in entities.Documents.Where(p => p.ProductId == ProductId && p.DocTypeId == DocTypeId && p.AvailableForUse == true && p.Status == "Approved") orderby (d.Description) select d).ToList();
return View(documents);
}
There's a pretty comprehensive solution here: http://ajaxpatterns.org/Unique_URLs
I assume you want to "change the url" so that the Back button works in the browser to navigate between the different products. You can't actually change the URL without a postback, but you can change the url's Hash value. By changing the Hash value you will be able to support the browsers Back button just like the URL itself was changed but without any postbacks.
In the following URL:
http://site/page#SomeValue
The Hash value is "#SomeValue".
You can set the Hash using "document.Hash" in JavaScript.
To make it much easier to work with the "document.Hash" value and setup a function to get notified when it changes, I create the jHash project.
You'll probably want to look at jHash to help you do what you're looking for.
http://jhash.codeplex.com/

Problem binding action parameters using FCKeditor, AJAX and ASP.NET MVC

I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper:
<% using (Ajax.BeginForm("AddText", "Letters",
new AjaxOptions() { UpdateTargetId = "addTextResult" }))
{%>
<div>
<input type="submit" value="Save" />
</div>
<div>
<%=Html.TextArea("testBox", "Content", new { #name = "testBox" })%>
<script type=""text/javascript"">
window.onload = function()
{
var oFCKeditor = new FCKeditor('testBox') ;
var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>';
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ToolbarSet = "Basic";
oFCKeditor.Height = 400;
oFCKeditor.ReplaceTextarea() ;
}
</script>
<div id="addTextResult">
</div>
<%} %>
The controller action hanlding this is:
[ValidateInput(false)]
public ActionResult AddText(string testBox)
{
return Content(testBox);
}
Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor.
If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected.
Am I doing something wrong?
If not is there a suitable/straight-forward workaround for this problem?
The problem is unrelated to MVC but caused by using FCKeditor in conjunction with AJAX. To fix in the code above I added the following to the submit button's onclick event:
<input type="submit" value="Save" onclick="FCKeditorAPI.GetInstance('TestBox').UpdateLinkedField();" />
For more information see here.

Resources