CORE 2 MVC Ajax redirect to display a view - asp.net-core-mvc

I have an application that uses the jQuery Datatable and I want to click on a row, pick up the id, and then bring up a view that allows for editing of that view and updating the underlying database.
Ajax gets me to the controller-action that for the edit view but I can't get the view itself to display. Instead, the controller action just returns to ajax. I've tried numerous tactics with no joy. Here is a simple example based upon a standard CORE template:
#section scripts{
<script>
$(document).on('click', 'button.number', function () {
alert($(this).val());
$.ajax({
method: 'GET',
url: '#Url.Action("About", "Home")'
});
});
</script>
}
<h3>Home Page</h3>
<div>
<button href="#" type="button" class="number" id="one" value="1">1</button>
<button href="#" type="button" class="number" id="two" value="2">2</button>
</div>
Running the debugger shows that About action is called OK but the view isn't rendered - it just returns to ajax. I've tried all sorts of redirection but any "return" just goes back to ajax.
Is there away around this or perhaps a better way to get from the JS to the controller-action? Thanks

Related

Controller returning PartialView overwriting entire View

I'm POSTing and trying to re-load a partial view with the new data using Ajax like this:
Index.cshtml
<div id="left-column">
#Html.Partial("~/Views/Project/_ProjectList.cshtml", Model.ProjectList)
</div>
~/Views/Project/_ProjectList.cshtml
#using (Ajax.BeginForm("Create", "Project", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "left-column"
}))
{
<h3>Create a new project</h3>
<div class="form-group">
<label for="new-project-name">Name</label>
<input type="text" class="form-control" id="new-project-name" name="Name" placeholder="Example" />
</div>
<button type="submit" class="btn btn-primary">Create Project</button>
Cancel
}
Then my Controller returns the PartialView after some db work:
[HttpPost]
public PartialViewResult Create(Project newProject)
{
db.Projects.Add(newProject);
db.SaveChanges();
var projectList = db.ProjectLists.SingleOrDefault(pl => pl.Id == 1);
return PartialView("~/Views/Project/_ProjectList.cshtml", projectList);
}
I would expect the _ProjectList partial view to load into the #left-column element with the new projectList passed in by the Controller, but instead, the entire View is being overwritten, so the entire body of the new HTML source looks basically like this:
<body>
<!-- all the stuff from the _ProjectList partial -->
</body>
It's worth noting that after the partial view returns, the URL reads /Project/Create, which I wouldn't expect.
I've included jquery-validate and jquery-validate-unobtrusive, and the console isn't showing any errors, so that shouldn't be the problem.
Any idea what's going on?
When using Ajax.BeginForm helper method to do ajax form posting, you need to include the jquery.unobtrusive-ajax.js file as well. This file has the code to handle the submit button click event and send the form asynchronously rather than doing the normal form submit.
If you do not include this file, the form submit will be normal. My guess is that you missed to include this file and hence missing the ajaxified form submit experience.
So make sure to load this file after jQuery
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Here is the link to nuget page if you want to add this file via nuget package manager.
Benjy got it in a comment above. It was a jQuery version issue. I'm running 3.1.0, and jquery.unobtrusive-ajax stopped working with jQuery version 1.9.

Working with mvc partial view and history.js

I'm using history js, https://github.com/browserstate/history.js/ to and Mvc Partial view, here is my code
In Partial Home
<a id="CreateUser" class="btn btn-primary">Create User </a>
and in my #section scripts to push new url and load partial content in 'state change event'
$('#back').click(function (e) {
History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
});
in contoller there is also logic to load partial view if its ajax call and full view if not, this is to protect from user if they press refresh when in ~/System/User/Create/.
any way my script onClick script in section doesnt work user in /System/User called from Partial View or Ajax, I can solve this by attaching OnClick Event inside outside #section scripts so it became like this:
<a id="CreateUser" class="btn btn-primary">Create User </a>
<script>
$('#back').click(function (e) {
History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
});
</script>
#section scripts
{
<script>
$('#back').click(function (e) {
History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
});
</script>
}
but this is redundant and pain to maintain I know this happend because #section doesnt work with Ajax/Partial, anyway is there's cleaner alternative other than this.
Nevermind findout that '.click' need to be rebind after loading ajax, but with .on('click' there is no need to rebind event handler, so I now just need script on click event in global js.

Sync up server side control from JavaScript

I have the following scenario:
I have two panels, with links to switch between the two, these links DON'T post back the page, they call some JavaScript code that fades in and out the panels, changing their visibility.
In either panel I have a button that posts back the page, what happens is, after I fade in the second panel, my viewstate is invalid and my postback fails.
Is there a way to make my viewstate valid from JavaScript synching the visibility of these two panels? Or do I have to postback for this to work? If so, can I postback without the page blinking in my face and nicely fade the panels?
EDIT: This is somewhat the code that I have, obviously I have a bunch of controls inside the divs
<div id="step_one" class="lt-step-1">
<asp:Button Text="Entrar" ID="btnPost1" OnClick="btnPost1_Click" ValidationGroup="Step1Val" CssClass="btn btn-primary lt-width-5" runat="server" />
<span class="icon-repeat"></span>Step Two
</div>
<div id="step_two" class="lt-step-2 hide">
<asp:Button Text="Confirmar" ID="btnPost2" OnClick="btnPost2_Click" ValidationGroup="Step2Val" CssClass="btn btn-primary lt-width-5" runat="server" />
<button type="button" id="btn_cancel_step_two" class="btn">Cancelar</button>
</div>
<script>
require(['jquery', 'bootstrap'], function ($) {
'use strict';
var $stepOne = $('#step_one'),
$stepTwo = $('#step_two'),
$allSteps = $('[id^="step_"]'),
$link_Step_Two = $('#link_Step_Two'),
$btnCancelStepTwo = $('#btn_cancel_step_two'),
$link_Step_Two.on('click', function () {
$allSteps.hide();
$stepTwo.fadeIn();
});
$btnCancelStepTwo.on('click', function () {
$allSteps.hide();
$stepOne.fadeIn();
});
});
</script>
Sorry, but I don't have enough points to just add a comment yet after Gnani above. If it is just losing the jquery events, use the jquery delegate function against the form element. Delegate will automatically hook up your events against your selector, even for elements that come into existence in the future, like when MS Ajax recreates your links. I use this trick all the time. Something like:
$("form").delegate('#link_Step_Two', 'click', function() {
// Your code.
});
$("form").delegate('#btn_cancel_step_two', 'click', function() {
// Your code.
});

MVC2 C#: How can I populate a contentplaceholder with html from a file?

So.. The issue I have came across is I am migrating a client's web app to MVC2, and the original method for displaying html content is not capable of working with MVC so I am needing to update it. The functionality I need is like so: There is a side nav that will contain the actions, and say the user clicks on "FooBar" it will populate the "mainContent" placeholder with the "FooBar.html" file from a document directory. I would like to do this with no postbacks as well if it is possible. Any ideas?
You may use jQuery ajax to load the pages when user clicks on the link. load() function will be ideal here.
It is just HTML and javascript. Nothing specific to ASP.NET MVC
//Include jQuery library
<div>
<a href="Home/about" class="aLink" >About</a>
<a href="Home/FAQ" class="aLink" >FAQ</a>
<a href="Home/Contact" class="aLink" >Contact</a>
</div>
<div id="mainContent">
</div>
<script type="text/javascript">
$(function(){
$("a.aLink").click(function(e){
e.preventDefault(); // prevent the default navigation behaviour
$("#mainContent").load($(this).attr("href"));
});
});
</script>

C# ASP.NET MVC AJAX Login Form

I am using the MVC Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId="updateajax" }) <div id=updateajax/> so it only updates to that area. The login form is the ajax.beginform. But can you cancel the AjaxRequest inside the controller. What I wanted is that when I am loggin in the ajax, it will only update the validations but when the login is successful I want the whole page to redirect or update again. In my controller I return the entire page when the login is successful but that put the whole content inside the updateajax div. What can I do to solve this problem? I just want to stop the ajax call when the login is successful.
You sort of have to either redirect or update the whole body of the page.
Or you can wrap the whole body content in a div and ajax update that one. My suggestion is to go ahead and redirect, because if you have scripts that run on load, you would have to manually call them.
<body>
<div id="ajaxUpdatedPanel">
<% using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions {
UpdateTargetId="ajaxUpdatedPanel",
OnSuccess = "redirectTo" }) { %>
....
....
<script type="text/javascript">
function redirectTo() {
window.location = "your_redirect_url";
}
</script>
<div>
</body>

Resources