|
How can I call the MVC Controller using jQuery? and one more thing is, can't I call the cshtml page directly using jQuery, because I want to avoid one extra call from cshtml to MVC then MVC to Web Api, instead of that I want to directly call cshtml from button click, that cshtml calls the Web Api directly?
Means I want to avoid MVC Controls calls, instead I want to call the cshtml and then Web Api directly? Am I supposed to do that? If I can can you please give me a small script or some suggestion or Link.
If I am not supposed to call Web Api directly from cshtml then please let me know then please help to call the MVC action method from the button click of the other cshtml page using jQuery.
Thanks a lot my friend.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
A view or .cshtml page won't render without a controller action result, thus MVC.
Yes, you can call a controller action using JQuery. I have a controller called Ajax in which I have JsonResults instead of ActionResults.
I call the JsonResult using $Ajax and send it a model but using primitives, and just return a model "return Json(modelName);"
If it ain't broke don't fix it
|
|
|
|
|
There are various examples of calling controller actions via jQuery here
Useful Way to Call Controller Actions From HTML Using jQuery[^]
I don't really understand what you mean by call the cshtml and then webapi. The reason you can't call cshtml pages directly is because they are just templates, they don't contain all the information you need to render html. Let's say this is in my view
<p>Hello @Model.FirstName</p>
If I were to navigate to that view directly what would appear on the screen? The reason we call actions and not views is because actions combine all available inputs (from the Request, the Session, Databases etc) with the template held in the view to output valid HTML.
You can call a WebAPI directly from a view as long as it's via javascript. You *can* put server-side code in a view to call an API but you shouldn't, it breaks the rules of MVC. So put javascript code in Views if you must, but the only server code should be what is needed to show data from the model, eg a for loop like
@foreach(SearchResult r in Model.Results)
{
<p>@r.Name</p>
}
|
|
|
|
|
Hi,
Yes I did it but still the new page is not rendering.
My default page (that's first page of the application) is: http://localhost:55429/BSCSecurityAddressBookWeb/Employee, means Employee.cshtml is loading, but when I clicked on the button to load a different Page, it goes into the Controller (MultiJobChange) and its View page and then it goes the Partial Page but stays with the same Old page content (ie Employee.cshtml), why is it not rendering the new page (MultiJobChange.cshtml) that it is supposed to when I called as below:
$("#btnMultiJobChange").click(function (event) {
$.get("http://localhost:55429/BSCSecurityAddressBookWeb/MultiJobChange/", null, function (data) {
//alert(data);
});
Any help would be very helpful thanks in advance.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Maybe because you're not doing anything with the response.
If you uncomment the alert(data); line, do you see the HTML from the MultiJobChange page in a messagebox?
You'll need to do something with the response in the callback. Or, you could try using $.load()[^] instead.
Of course, if you just want to navigate to another page, rather than creating a Single Page Application, there are much easier ways to do it.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Yes I am seeing the Page html in string format if I uncomment the alert, but how to to render it I am not able to understand,
And another thing is I am using .load() method but still its not able to load the new Page still it stays on the same Old page, but .load is not even going into the Action method even, at least the Get method was getting into the Action method.
please help me my friend, any help would be much appreciated - thanks in advance buddy
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
-- modified 27-Jun-17 19:51pm.
|
|
|
|
|
$.get is for when you want to download the html of that url and do something with it in your code, it won't show that page in the browser or navigate to it. If MultiJobChange is a partial view you need to inject the html into the page somewhere.
public class MultiJobChangeController : Controller
{
public ActionResult Index()
{
return PartialView("~/Views/MultiJobChange/_Index.cshtml");
}
}
<div id="target"></div>
<script>
$(document).ready(function () {
$.get("@Url.Action("Index", "MultiJobChange")", function (data) {
$("#target").html(data);
});
});
</script>
or you can use load if you only want to load the html into the div
$(document).ready(function () {
$("#target").load("@Url.Action("Index", "MultiJobChange")");
});
|
|
|
|
|
OK Got it there nothing like Response.Redirect or Transfer in html only thing is I need to inject it. Its old WebFarms model man, sorry my friend and thank you very much too.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Ok, what you want is window.location.href
window.location.href = '@Url.Action("Index", "MultiJobChange")';
|
|
|
|
|
Hi,
If its not a partial View, but View itself, can I use it as well
public class MultiJobChangeController : Controller
{
// GET: MultiJobChange
public ActionResult Index()
{
return PartialView("~/Views/MultiJobChange/Index.cshtml");
}
}
Instead of
public class MultiJobChangeController : Controller
{
// GET: MultiJobChange
public ActionResult Index()
{
return PartialView("~/Views/MultiJobChange/_Index.cshtml");
}
}
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Hi all,
I am getting the following error when I run my Web Application, the error started coming after I got new laptop from my Organization and I moved the code from the Old machine to new machine. I tried to check in the Log file that it mentions but there is no log files created. Any help could be very helpful, thanks in advance.
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information:
Module IIS Web Core
Notification: Unknown
Handler: Not yet determined
Error Code: 0x80070003
Config Error: Cannot read configuration file
Config File: \\?\C:\Users\aaleem01\Desktop\Angular2Apps\BSCSecurityAddressBookWeb\BSCSecurityAddressBookWeb\web.config
Requested URL: http://localhost:55429/BSCSecurityAddressBookWeb/Employee
Physical Path:
Logon Method: Not yet determined
Logon User: Not yet determined
Request Tracing Directory C:\Users\aaleem01\Documents\IISExpress\TraceLogFiles\
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
"Config Error: Cannot read configuration file
Config File: \\?\C:\Users\aaleem01\Desktop\Angular2Apps\BSCSecurityAddressBookWeb\BSCSecurityAddressBookWeb\web.config"
Isn't that quite explicit? Does that file exist? Can it be read by your site? If you have copied those files from another machine there could be security issues on the files.
|
|
|
|
|
The file doesn't exist there, because of the Project moved from different location, then there is another problem, how can I change this, I am using default IIS Express, I didn't create an Explicit Virtual Directory in the IIS but clicked on the Create Virtual Directory, it says directory is created successfully. But I am not understanding why is it still looking for the Web config in the older folder.
Any help would be lot graceful thanks in advance.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Most likely, your application pool is running as a user which doesn't have read permissions to the folder. That's quite common with paths stored within your user profile.
You need to change the NTFS permissions on the folder to grant read access to the IIS_WPG group.
File and Folder Permissions[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have a form called "get started" that's on about 10 pages wrapped in form tags on views.
Instead of writing 10 post action results that are the same, I'd like to consolidate them into 1 called "getStarted".
I remember seeing or stumbling upon a how to months ago, but now I can't find it using search.
What I've tried:
So I'm experimenting here, tried the ActionResult but needed a view page for it to work. I haven't made a view yet.
Tried a controller action that is void, but it says page not found after posting. The post actually works and sends the emails and so forth. but I can't do a redirect because I have to action result as a return value.
Any other ideas out there?
If it ain't broke don't fix it
|
|
|
|
|
jkirkerx wrote: I can't do a redirect because I have to action result as a return value
The RedirectResult class[^] is an ActionResult which redirects the response to another URL.
The Controller base class defines several helper methods you can use to redirect the response:
For example:
public ActionResult GetStarted(YourViewModel data)
{
...
return RedirectToAction("Index", "Home");
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I ended up creating a view file for the action that is quite elegant looking, and let's the user know that the form was submitted successfully.
In hindsight, it I would of got it working, then I had to deal the form again, or double clicks perhaps, multiple form submissions.
If it ain't broke don't fix it
|
|
|
|
|
I'm looking some examples of forcing HTTPS or force HTTP in attribute form for use in the controller.
I found The Westwind guy "Rick" example and gave it a shot and it works. But once it turns HTTPS on, it always on. I didn't see the point of it.
WestwindToolkit/RequireSslAttribute.cs at master · RickStrahl/WestwindToolkit · GitHub
I added the debug part, which works fine, and I'm testing in production mode.
I'm not interested in securing the entire program in HTTPS or SSL, but just parts of it.
My question is where or how would be a good way to go back to HTTP in the code example above?
public RequireSslAttribute(string appSettingsKey)
{
string key = ConfigurationManager.AppSettings[appSettingsKey] as string;
bool debugEnabled = HttpContext.Current.IsDebuggingEnabled;
RequireSsl = false;
if (!string.IsNullOrEmpty(key))
{
key = key.ToLower();
if (key == "true" || key == "1")
if (debugEnabled == false)
RequireSsl = true;
}
}
If it ain't broke don't fix it
|
|
|
|
|
I'm not sure why you'd only want part of your site to be served over HTTPS. If you already have a certificate set up, why not serve the whole thing over HTTPS, and be more secure by default?
The reason we don’t have a [RequireHttp] attribute in MVC is that there’s not really much benefit to it. It’s not as interesting as [RequireHttps] , and it encourages users to do the wrong thing. For example, many web sites log in via SSL and redirect back to HTTP after you’re logged in, which is absolutely the wrong thing to do. Your login cookie is just as secret as your username + password, and now you’re sending it in cleartext across the wire. Besides, you’ve already taken the time to perform the handshake and secure the channel (which is the bulk of what makes HTTPS slower than HTTP) before the MVC pipeline is run, so [RequireHttp] won’t make the current request or future requests much faster.
If you really feel like making parts of your site less secure, you'll need to write your own filter attribute. It's not difficult - you just need to modify the RequireHttpsAttribute[^] to redirect to HTTP instead of HTTPS.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RequireHttpAttribute : FilterAttribute, IAuthorizationFilter
{
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null) throw new ArgumentNullException(nameof(filterContext));
if (filterContext.HttpContext.Request.IsSecureConnection)
{
HandleHttpsRequest(filterContext);
}
}
protected virtual void HandleHttpsRequest(AuthorizationContext filterContext)
{
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException();
}
string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I wanted unsecure pages for things like customer reviews and picture portfolios.
My web servers have Xeon CPU's with AES instructions, so SSL it not so CPU intensive like my last web servers,
I just wanted to ease the load on the CPU so it can focus on image files.
I'll take a look at your example right now.
If it ain't broke don't fix it
|
|
|
|
|
Well that took me awhile to understand and figure out. Guess I should of asked how to use it.
Anyways thanks Richard!
If it ain't broke don't fix it
|
|
|
|
|
What is the best practice in .NET with Web API? Especially Web REST API. Should a REST API return exception in response body when an exception happens?
For sure I will return a 500 or similar HTTP status. But when I response with this error code what are the best practice? Or even better what is the specification or REST API about this?
- return the exception (what I do)
- return en empty response body?
- return an empty of default JSON object?
- something else?
FYI I'm working on a Web pragmatic REST API in C# .NET that is consumed by a Ruby on Rails team and I'm not sure Ruby code can handle these exception message easily.
|
|
|
|
|
WEB API should return status code in the header and any content in the body.
For example, if the request is successful then set the status code to 200 in the header and send the result in the body.
If the request is failed , then set the corresponding status code in the header ( for example 500 etc...) and send additional information in the body.
|
|
|
|
|
Please I am working with MVC C#. I have a html table that is being populated from a database Table and its working fine, but my question is i want to save that same table to another database table. Please can anyone help me as its urgent. Thanks
AOD
|
|
|
|
|
Please do not post duplicate contents.
Also, do you need to save save html markup here to database? or contents you generated inside html table.
modified 20-Sep-20 21:01pm.
|
|
|
|