redirect to action asp.net MVC - 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.

Related

Display a "Details" view as a modal popup

I have this code to show info about a certain product registered in my database.
Button that triggers my Details Controller:
#Html.ActionLink("Details", "Details", new { id = prod.ID }, new { #class = "btn btn-danger" }) |
Controller code
public ActionResult Details(int? id)
{
PRODUCTS pRODUCTS = db.PRODUCTS.Find(id);
if (pRODUCTS == null)
{
return HttpNotFound();
}
return View(pRODUCTOS);
}
I want to display that "Details" view in a modal popup. I tried to create my modal in the same view where i have my "Details" button, but i can't pass my product id to the controller and it only shows me an empty view.
To show data inside a modal popup, you need an action method which returns HTML markup needed for the modal popup. So the first step is to make an action method which returns a partial view result.
public ActionResult Details(int id)
{
var product = db.PRODUCTS.Find(id);
if (product== null)
{
return HttpNotFound();
}
return View(product);
}
In the above simple example, I am querying the entity and passing the entity object directly to my view using the PartialView method. If you have a view model for your view, please use that.
Now in the Details.cshtml view, we will write code to return the HTML markup needed for the modal popup. Since we are passing the PRODUCTS object to the view, we will make sure our view is also strongly typed to that type.
#model YourNamespaceHere.PRODUCTS
<div id="modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"> Details</h5>
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h2>Hello from #Model.Name</h2>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In the above example, I am simply printing the Name property value of PRODUCTS object in the modal body. You may update it to render other properties as needed.
Now we will make some changes to our HTML markup being rendered for the product. We need the click event on the details link to open the modal dialog. So let's first give some attributes to the link element, which we can later use to wireup the click event. Here I am going to add an additional CSS class to the links, modal-link.
#Html.ActionLink("Details", "Details", new { id = prod.ID },
new { #class = "btn modal-link" })
Now let's write some JavaScript code to listen to the click event on the link element with the modal-link CSS class, read the the href attribute value of the element and make an Ajax call to that URL and render the response of that call to build the modal dialog.
$(function () {
$('body').on('click', 'a.modal-link', function (e) {
e.preventDefault();
$("#modal").remove();
// Get the Details action URL
var url = $(this).attr("href");
//Make the Ajax call and render modal when response is available
$.get(url, function (data) {
$(data).modal();
});
});
});
I am using CSS class as the selector here, you can use any other selector as you wish
i think you should use jquery ajax to call action on click your button or action link and get your model as json result and return it then first clean your modal data and fill it with new result and at the end show your modal......

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>

Render partial later after page loads

Using Rails 3.2. Let's say I have the following view:
<div class="content">
<div class="main">
<h1><%= #shop.name %></h1>
<p><%= #shop.description %></p>
</div>
<div class="sidebar">
<%= render 'teasers' %>
</div>
</div>
Is there a way to just load the page first, then load the teasers later? Reason being so is because teasers takes some time to query (I have already optimized the query).
I personaly have a pre-defined system for this kind of behavior:
This (coffeescript) Javascript code is executed at each rendering of a page:
$('.ajax_load').each (index, element) ->
e = $(element)
$.get e.data('url'), (data) =>
$(document).replace(e, data)
So each element in my page responding to the class "ajax_load" is actually called by ajax, example:
%div.ajax_load{ data: { url: users_path } }
This will display at first a div with a class ajax_load, and will send a request to users_path and replace the div with the response's content.
This is translated coffeescript:
$('.ajax_load').each(function(index, element) {
var e,
_this = this;
e = $(element);
return $.get(e.data('url'), function(data) {
return $(document).replace(e, data);
});
});
How about removing the teasers partial from the view and initially just displaying the page without it. Then using javascript, make an AJAX call to the server.
You can use wiselinks to simplify your life.

How can I use a div element to redirect with MVC htmlhelper?

I have a bunch of div elements that look like this at the moment:
<div onclick="window.open('Technology','mywindow');" class="grid" id="technology">
<p class="category-title">Technology</p>
</div>
I would like to get rid of the window.open and instead use MVC htmlhelper like actionlink to redirect users when they click on the div element. How can I do that?
The correct way to handle this is with a simple anchor tag.
Replace "myAction" and "myController" with the location you want to redirect the user to.
<a href="#Url.Action("myAction", "myController")">
<div class="grid" id="technology">
<p class="category-title">Technology</p>
</div>
</a>
ActionLink will return an anchor tag. What you can do is, you can assign the URL to the attribute of div via #Url.Action(). Then in JavaScript you can grab this URL and open a new window.
<div data-action ="#Url.Action("Text", "ActionName")">
<p class="category-title">Technology</p>
</div>
And in jQuery
$('div').click(function () {
var url = $(this).attr('data-action');
if(url !== undefined)
window.location.href = url;
});
Alternatively in pure JS,
document.document.getElementsByTagName('div').onclick = function(e) {
var url = this.getAttribute('data-action')
if(url !== null)
window.location.href = url;
}
This way, all divs having the data-action attribute will redirect to new page.

list is not refreshed in mvc 3 view

I have an asp.net view which has two partial views. One for edit information and other one for displaying list of changes that were made. When I hit the update button, the list is not updated. I used ajax.begin form. How can I do this?
Main view has like this:
<div class="accountdetails1">
#Html.Action("UpdateAccountDetails", new { dispute = dispute })
</div>
<div>
list of changes
#Html.Action("GetAccountAudit")
</div>
updateAccountDetails is like this in start:
#using (Ajax.BeginForm("UpdateAccountDetails", new AjaxOptions
{
LoadingElementId = "loading",
LoadingElementDuration = 2000,
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
}))
{
and functions are like this:
<script type="text/javascript">
function OnSuccess() {
var div = $('#dvMessage');
div.html('');
div.append('Account Information has been updated.');
}
function OnBegin() {
var div = $('#dvMessage');
div.html('');
}
</script>
to show success or failure of update Do I need to update change list in success method? Please suggest
#Ajax methods works in following way:
#Ajax.ActionLink - requests HTML from pointed action via AJAX and puts result in HTML element with id equals to UpdateTargetId value specified in AjaxOptions.
#Ajax.BeginForm - gets the all inputs and selects and other form elements inside using(Ajax.BeginForm()) { .. } and submits it to specified action (using AJAX) then puts response to HTML element with id specified in AjaxOptions.UpdateTargetId property.
So you need something like
<div id="myContainer" >
#using(Ajax.BeginForm("yourActionToProcessEdits", new AjaxOptions { UpdateTargetId = "myContainer" }))
{
.. Form for edit information
#Html.EditorFor(m => m.EditMe)
...
<input type="submit" value="Update" />
.. Display changes here
#Html.Raw(Model.MyChanges)
}
You need to request the GetAccountAudit action to return the list. The beginform is only requesting the UpdateAccountDetails action.
You could do a jquery ajax request in the onSuccess function to request the GetAccountAudit action and update the html.
Could the two actions be combined so that the list would be returned in the UpdateAccountDetails view?

Resources