Display view result in a div in ASP.NET MVC - 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?

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>

Show different web pages in multi view using link button

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.

ASP.NET MVC.NET JQueryUI datepicker inside a div loaded/updated with ajax.actionlink

I'm trying to incorporate jqueryUI's datepicker inside a partialview like this:
<% using (Ajax.BeginForm("/EditData",
new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "div1" }))
{%>
Date:
<%= Html.TextBox("date", String.Format("{0:g}", Model.date), new { id = "datePicker"})%>
<% } %>
<script type="text/javascript">
$(function() {
$("#datePicker").datepicker();
});
</script>
When I directly call the url to this partial view, so it renders only this view the datepicker works perfectly. (For the purpose of testing this I added the needed jquery and jqueryui script and css references directly to the partial view)
But if I use a Ajax.Actionlink to load this partial view inside a div (called div2, submitting the above form should update div1) like this:
<div id="div1">
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" } )%>
</div>
<div2>placeholder for the form</div>
The datepicker won't appear anymore.
My best guess is the javascript included in the loaded html doesn't get executed,
($(document).ready(function() {
$("#datepicker").datepicker();
}); doesnt work either
If that's the case how and where should I call the $("datepicker").datepicker(); ?
(putting it in the ajaxoptions of the ajax.actionlink as oncomplete = "$(function() {
$('#datepicker').datepicker();});" still doesnt work.
If that's not the case, then where's my problem?
The answer given by veggerby probably will be working in the given scenario, therefor i marked it as correct answer.
My problem here was that the javascript is in a portion of html being dynamicly loaded thrue ajax. Then the loaded javascript code wont be picked up by the javascript interpreter (or whatever im supposed to call the javascript handling on the clientside).
In my case veggerby's sollution wouldnt work either but that's because in my app i even loaded that piece of html+javascript thrue ajax. which results in the same problem.
i didnt feel like putting the javascript in the first normally loaded page, since it doesnt always load the same piece of app (thus possibly executing code when its not needed).
i resolved this by creating a sepperate .js script which is included in the site.master:
function rebindJQuery(data) {
jQuery('#div2').html(data.get_data());
jQuery('#datepicker').datepicker();
return false; //prevent original behavior, in this case folowing the link
}
which gets executed by
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" , oncomplete="rebinJQuery" } )%>
i have yet to find a way to get the UpdateTargetId into my rebindJQuery(data) function, so this can be more generic. Nontheless this solves my problem. (and a couple of compairable questions asked here on stackoverflow)
I don't know why that does not work, but you could skip using the Ajax.ActionLink and instead use JQuery on itself to do this task, i.e.:
<div id="div1">
<%= Html.ActionLink("Edit", "/EditData", new { id = Model.id } )%>
</div>
<div2>placeholder for the form</div>
<script type="text/javascript">
$(document).ready(function() {
$("#div1 a").click(function() {
$.get(
$(this).attr("href"),
null,
function (data) {
$("#div2").html(data);
$("#datepicker").datepicker();
});
return false; // to prevent link
});
});
</script>
jQuery live events might be useful.
http://docs.jquery.com/Events/live

ASP.NET MVC jQueryUI datepicker not working when using AJAX.BeginForm

I have an ASP.NET MVC Partial View that contains a Html.TextBox that is configured to use the datepicker from JQueryUI. This is done by ensuring the style is set to .datepicker. This all worked fine. However I have changed my forms to Ajax.BeginForm and included a Ajax.ActionLink that displays it after clicking on the link. Since adding this the datepicker does not display. In fact no JavaScript that previously worked is now even being invoked after a returning a partialview from the controller. Even if i PUT THE JavaScript/JQuery in the partial view itself it still does not use it. I really am confused, can someone please help?
Examples shown below
<div id="claims">
<div id="divViewClaims">
<% Html.RenderPartial("ViewClaim", Model.Claims ?? null); %>
</div>
<br /><br />
<div id="claim">
<% Html.RenderPartial("AddEditClaim", new Claim()); %>
</div>
</div>
Action Link, when clickon calls Controller Action to return PartialView, The JavaScript called on the OnSuccess fires but nothing else, that previously was hooked up by the document.ready function. All my scripts are in seperate files and referenced in master page.
<%= Ajax.ActionLink(string.Format("Add A{0} Claim", Model.Count > 0 ? "nother" : string.Empty), "AddClaim", "Driver", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "claim", OnSuccess="showAddClaim" }, new { #class = "ControlLink" })%>
Controller Action
public ActionResult AddClaim()
{
return PartialView("AddEditClaim", new Claim());
}
Partial View, which shows the textbox with the style set to datepicker
<% var ajaxOptions = new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divViewClaims", InsertionMode = InsertionMode.Replace, OnSuccess="hideAddClaim" }; %>
<% using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { #name = "ClaimControl", #id = "ClaimControl" }))
{ %>
<fieldset>
<legend><%= Model.Id==0?"Add":"Edit" %> Claim</legend>
<p>
<label for="Title">Claim Date</label>
<%= Html.TextBox("Date", Model.Date.ToString().TrimEnd('0', ':', ' ') ?? "", new { #class = "datepicker" })%>
</p>
I appreciate any help on this.
If the element is created after document.ready you should re-match the element to jQuery.
Check out jQuery Live
What works for me is to use the OnSuccess property from the AjaxOptions. So, your code could be like this:
using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { #name = "ClaimControl", #id = "ClaimControl", OnSuccess="the_javascript_function_below" })
where the_javascript_function is the name of a function that does this:
$(".datepicker").datepicker();

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