Updating #RenderBody using jquery in mvc - javascript

Coming from a webform background using ajax I am trying to create similar with mvc.
I have worked out what the controller, view and models do.
What i would like to do now is that when my user clicks a button an jquery call is made to update the view - hence not refreshing the entire page.
Much like a master/child design in webforms.
I have googled and I have tried a couple of things but I get a 404. I have checked and i am sure I am calling things correctly.
This is my jquery function:
$("#divProductsBanner").click(function () {
var currentObject = $(this).text();
$.get('#Url.Action("Lite", "Service")', { theName: currentObject });
});
Where 'Lite' is my view and 'Service' is my controller.
my Service.cs controller looks like this:
public ActionResult Lite()
{
return View();
}
and I have a view called 'Lite' under my 'Service' folder under the 'Views' folder.
when I click that button i get this error:

You can not use C# code in JS file. You can render the URL in the hidden field and use it
Something like
#Html.Hidden("MyURL", #Url.Action("Lite", "Service"))
In js
$("#divProductsBanner").click(function () {
var currentObject = $(this).text();
$.get($("#MyURL").val(), { theName: currentObject });
});
Refer the links and change your code accordingly.
Asp.Net Mvc Url.Action in external js file?
Use Seprate js File And use Url Helpers in it with ASP.NEt MVC 3 and Razor View Engine

Related

Passing data from Partial View to its parent View in asp.net core mvc

This link have a similar answer which works fine but some changes required above answer works fine, but my objective is a little bit different, I wanted to pass the variable from partial view who contains image URL, I want to use that URL in the main view somewhere. the scenario is, calling ajax to load the partial view and displaying in modal, partial view having a lot of ajax which calling controller for fetching folder and files from the server, on the response of ajax I got an image file URL in the partial view, now I want to pass that URL into the main view, how to do that?
the main view -> works fine
enter code here
$(document).ready(function (){
$("#button1").click(function ()
{
$("#modalbodypopup").load("/ControllerName/GetPartial");
jQuery.noConflict();
$('#imagePopup').modal('show');
});
});
</script>
controller -> works fine
enter code here
public IActionResult GetPartial()
{
return PartialView("~/Views/Shared/_FileManager.cshtml");
}
partial view calling different controller who returning HTML who have a lot of link and folders name and image file name now on the calling of ajax from the partial view, after a successful response, I got a file URL in the variable inside partial view javascript side which I want to pass to the main view because I am displaying that image there.
There are a couple of ways you can do this. Your GetPartial() method can do:
return PartialView("_FileManager");
And as long as the file is in the shared folder, MVC works out the path.
You can also return the contents of a file directly:
var file = File.ReadAllBytes(..);
return File(file, "image/png");
This allows you to stream the image url directly into the browser.

How to call javascript function in a JS file to a controller using ASP.Net MVC?

I'm having a problem trying to call a javascript function in a JS file to a controller. I wanted to use the function in the JS file then return the value to a controller who calls that function.
Here is my code:
(JS File)
function getQueryString(url) {
var arrSplit = url.split('?');
return arrSplit.length > 1 ? url.substring(url.indexOf('?')+1) : '';
}
And I wanted to make a call like this in my controller.
(Controller)
private string DoSomething(){
getQueryString("http://sample.com");
}
Is is this possible? Or if ever do you have any suggestions or any possible workarounds?
First of all, MVC does not work that way. You cannot refer JS methods from your MVC controller. MVC controlled executes on the backend and just formulates your View. Once your HTML view is returned to the client, it executes there, And you JS is on the client-side. If you need to call a method in your JS on the browser side, from a server-side Controller, you need to use SignalR.

Getting parameters from query string

I am creating a web page using ASP.Net WebAPi, MVC and Knockout.
I have a normal MVC controller that loads the pages when I need them:
[Authorize]
public class AdminController : Controller
{
public ActionResult Clients()
{
return View();
}
public ActionResult ClientEdit(int? Id)
{
return View();
}
}
And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.
So, my knockout click event looks like this in my knockout view model:
self.EditClick = function () {
if (this.ClientId && typeof this.ClientId !== 'undefined') {
window.location.href = "/Admin/ClientEdit/" + this.ClientId;
}
else
window.location.href = "/Admin/ClientEdit/";
}
(It handles the 'Create New' button and the edit button, hence the 'if')
Once I redirect, the MVC controller loads the page, and the URL is:
http://localhost:49389/Admin/ClientEdit/1
I then load the knockout model, and would like to make an API call to get the data...
After my page loads, I want to bind the view model to the page. Here's my view model at the moment:
function AdminClientEditor() {
var self = this;
self.Name = ko.observable("");
self.ContactName = ko.observable("");
ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);
So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.
But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?
You can pass the id value to view via viewbag.
public ActionResult ClientEdit(int? Id)
{
ViewBag.ClientId=id;
return View();
}
and in the view's script section
var clientId="#ViewBag.ClientId";
alert(clientId);
// use this
If your javascript code which accesses this id value is inside a separate external js file, you may set this value to a js variable in your view and access it in your js file. Make sure to use namespacing to avoid global variable overwriting value issues.
So in your view
<script>
var myApp = myApp || {};
myApp.ClientId= "#ViewBag.ClientId";
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in the PageSpecificExternalJsFile.js file,
var clientId=myApp.ClientId;
//use this as needed
I'm not sure if this is the best way, but you can get the ID from the URL by using JS:
var id = GetID();
function GetID() {
var href = location.href;
var results = href.split("/");
return results[results.length - 1];
}
I've come up with this solution which works, but I am unsure if it's the best way. It seems pretty good.
I created a MVC ViewModel class in my application code, called 'GenericParameteModel', which at the moment, has a single parameter, "Id".
I then modified my page loading MVC method:
public ActionResult ClientEdit(int? Id)
{
var mv = new GenericParameteModel { Id = Id };
return View(mv);
}
On my View page, I added the model 'GenericParameteModel' to the View.
I created a hidden field, called 'ClientId' on the view.
<input type="hidden" id="clientId" value="#model.Id">
Then, within my knockout view model, I check if $("#clientId").val() has a value. If so, I do the $.get call, using that value, and populate my view model.
In doing so, all my initial page loads from MVC will have the ability to you the GenericParameteModel, and it will be a pattern for other pages. As it's a model, I can add new fields as my application requires.
This seems to work well. I'm unsure if this is an acceptable way as I am new to this (MVC to load views and the Knockout/WebApi to get the data after loading). But it seems neat and manageable.

asp.net mvc passing any data from a partial view that is rendered with $.get() to ContentPage

I am trying to make my web application like a desktop application.
I am also not using any _LayoutPage and #RenderBody().
I have a ContentPage as MasterPage and a tag named main
I am using ajax get method to render my views or partial views like this:
$.get(url).done(function (result) {
$("main").html(result);
});
I managed to inject my script and css files with javascript functions.
And now I want to pass some specific datas without using javascript functions.
It can be via using ViewBag, I guess.
I want to pass that data from my partialView:
ViewBag.BodyClass = "signup-page";
to my MainPage like this:
<body class="#ViewBag.BodyClass">
How can I do that?
A little note: Please ignore that I am a newbie and my low reputation
If you have a script manager ($.get) that calls your server to get the views and partial views, no problem.
When you request a URL, normally MVC calls a Controller and Action. In that action you can return content, view, partial view, file and so on...
You can create a new instance of a class model and pass to your partial view.
public ActionResult Index(string parameter1, string parameter2)
{
var model = new Models.ModelTest();
model.BodyClass = "some class";
return PartialView("_Page", model);
}
You will call some like this:
$.get("http://localhost/app/getviews?id=3422&parameter1=test&parameter2=foo")
In your view or partial view:
#model YourApp.Models.ModelTest
<body class="#Model.BodyClass">
I use that all the time.
I wrote that code on my partialView. It adds a class at ContentPage's body tag
$("body").addClass("signup-page");

Call an action from JS file instead of the view (MVC 4)

I'm using the MVC 4.
In my view i can simply get an action's url by using the: #Url.Action
Now i wanted to make a javascript file with all the view's javascript instead of writing it all in the view, the problem is i can't use the razor's stuff anymore.
so my question is how can i get the action's url from a javascript separated file?
You'll need to define a JavaScript variable within your view that you can then use in your script. Obviously this must be declared first.
I use a helper on my layout pages that has all these variables and a section for any I'd want specific to a page. Note these would come before any other script references before the body tag.
#Scripts.Variables()
#RenderSection("ScriptVariables", false)
The Scripts.Variables is something like this
#helper Variables()
{
<script language="javascript" type="text/javascript">
var ActionGetallAdmin = '#Url.Action("GetAll", "Admin")';
var ActionAccountLogin = '#Url.Action("Login", "Account")';
</script>
}
One way I did this before was to create views that served JS files (and CSS files, actually), instead of HTML files. This leverages the fact that views aren't necessarily HTML files all the time in the MVC paradigm.
You could do this by creating a controller for it:
public class AssetController : Controller {
protected void SetMIME(string mimeType) {
// implementation largely removed
this.Response.Headers["Content-Type"] = mimeType;
this.Response.ContentType = mimeType;
}
// this will render a view as a Javascript file
public void ActionResult MyJavascript() {
this.SetMIME("text/javascript");
return View();
}
}
Once you've done that, you can create a view (using the way you normally do it in ASP.NET MVC), and just write it up as Javascript. Remember not to use a layout, as you obviously don't want that.
Everything that views in MVC has to offer is available to you, so feel free to use models, et al.
#model IList<Entity>
#{
Layout = null;
}
(function ($) {
// javascript!
#foreach(var entity in Model) {
$('##entity.Id').on('click', function () {
console.log('#entity.Name');
});
}
})(jQuery);
Then you can wire that up using old-fashioned Razor in your other views.
<script src="#Url.Action("MyJavascript","Asset")"></script>
Which will roll out something like
<script src="http://your.domain/asset/myjavascript"></script>
Works like a charm. The views are dynamically created, of course, so be wary if you're nit-picky about that. However, since they are MVC controller actions and views, you can set cache options on them just as with any other view.
Uhm... I think you can define a special route, like "actionsjs", that points to an action.
routes.MapRoute(name: "actionsJs",
url: "actionsjs",
defaults: new { controller = "Home", action = "GetActions" });
In the action you've to set the content to the right type:
Response.ContentType = "text/javascript";
Then you'll return a specific View that will contains javascript code with some Razor inside.
#{
Layout = "";
}
$(function() {
var a = #(1 + 2);
});
At this point you'll able to add this "script file" to your site:
<script type="text/javascript" scr="#Url.Action("GetActions", "Home")"></script>
Should work.
If you want the root path, use a variable on layout and use that in JavaScript file, say
// In layout view
<script>
var rootPath = #Url.Content("~/")
</script>
User rootPath anywhere in your application JavaScript files
If you want to get full path of a controller with action then
// View
<script>
var url = #Url.Content("ActionName", "ControllerName")
</script>
use url in your JavaScript file.

Categories

Resources