Index ActionMethod in Home Controller would be called twice in ASP.Net MVC - asp.net-mvc

i created an ASP mvc 4 project with basic template and just with one Index view .
when i run the application , Index Method that belongs to Home Controller called twice.
i cant understand why
please help me
Thanks Alot
Index Method:
public ActionResult Index()
{
return View();
}
Index View :
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>

finally i found the problem
i always test my project on google chrome after changing browser and agin run the project on IE it did not occour the problem again
so my browser which was set in VS2012 , and its setting was the problem

Related

why does .net core "Return" verb inside a controller adds "plaintext.css" ?

I was doing some testing with MVC6 .net core, and did a quick hack to return a bootstrap html code by putting dirtyHTML directly inside a controller.
The HTML contains the official example of bootstrap inside a literal string.
Just a quick way of returning some bootstrap html, (as i experiment with controller functionality), to my surprise when i go to a page using a web browser, all html text is shown like plain text, its not rendered.
namespace WebApplication1.Controllers
{
public class MariaController
{
[HttpGet("/index")]
public string index()
{
string dirtyHtml;
dirtyHtml =
#"<!DOCTYPE html>
<html lang=""en"">
<head>
<title>Bootstrap Example</title>
<meta charset=""utf-8"">
<meta name=""viewport"" content=""width=device-width, initial-scale=1"">
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"">
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js""></script>
<script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js""></script>
</head>
<body>
<div class=""container"">
<h1>My First Bootstrap Page</h1>
";
return dirtyHtml;
}
}
When going to debug mode, initially they show the same asci text, but using firefox i see there is a line inserted before my page code:
<HTML><head>
<link rel="alternate stylesheet" type="text/css"
href="resource://gre-resources/plaintext.css"
title="Wrap Long Lines">`
So then i thought, let's look around in the solution and search for "Wrap Long Lines".. as to see where it comes from,... this is however not found.
So where does that come from ? (as the solution doesnt contain plaintext.css either). And more important to me, can it be disabled?.
I am not sure what you want to achive but following thing is way to go.
"Wrap Long Lines" and css related to that are internal to firefox browser.
You are saying that you return html and it display like html but it does not render html and for that do following thing.
[HttpGet("/index")]
public IActionResult index()
{
string dirtyHtml;
dirtyHtml =
#"<!DOCTYPE html>
<html lang=""en"">
<head>
<title>Bootstrap Example</title>
<meta charset=""utf-8"">
<meta name=""viewport"" content=""width=device-width, initial-scale=1"">
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"">
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js""></script>
<script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js""></script>
</head>
<body>
<div class=""container"">
<h1>My First Bootstrap Page</h1>
";
return Content(dirtyHtml,"text/html");
}
See I have return IActionResult and Use Content from return.
Reason for this is when you return string it will display as string and if it is html then it will become encoded as you did not tell browser content type so it consider "text/plain".
An alternative of #dotnetstep's way is using Produces attribute:
[HttpGet("/index")]
[Produces("text/html")]
public string Index()
{
...
}

How call jScript function in MVC view

I have this function in.js file:
function setValue(amount) {
if (amount === 0) {
.....
loanDriver._mem.loanValue = amount;
}
I like to call this in my MVC view and send this value to it : Model.ApprovedAmount
I tried this:
<script type="text/javascript">
setValue(#Html.Raw(Model.ApprovedAmount))
</script>
it is not working.
How I can do that?
Your existing code likely doesn't need the Html.Raw() call, but besides that it at least appears to be correct :
<script type="text/javascript">
setValue(#Model.ApprovedAmount)
</script>
There are a few things that you may want to look into to further troubleshoot this issue :
Check Your References
Firstly, make sure that the Javascript file that defines your setValue() function is being referenced prior to your existing <script> tag shown in your example. This is important as otherwise your page won't know what setValue()
is:
<script src='your-file-with-setvalue-defined.js'></script>
<script>
setValue(#Model.ApprovedAmount);
</script>
Use the Developer Tools
Check the Developer Tools (F12) within your browser, specifically the Network and Console tabs. These will reveal additional details about what exactly is going wrong (i.e. 404 errors, undefined functions, bad arguments, etc.).
Use the debugger
Consider using the debugger keyword within your setValue() function to see if it's being called and what the value that is being passed in looks like :
<script>
// Run this with your Developer Tools open and step into the function to
// see more
debugger;
setValue(#Model.ApprovedAmount);
</script>
Example
You can see a complete example here and seen below that demonstrates the basic idea behind this working as expected :
// HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new SampleViewModel(){ Amount = 42 });
}
}
// SampleViewModel.cs
public class SampleViewModel
{
public int Amount { get; set; }
}
// Index.cshtml
#model HelloWorldMvcApp.SampleViewModel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calling Function From Model</title>
</head>
<body>
<script>
function setValue(amount) {
alert(amount);
}
setValue(#Model.Amount);
</script>
</body>
</html>
assuming you are just doing it on the view, you can do something like this:
<text><b>some text:</b> </text> #Html.TextBox("something", null, new { "callsomefunction"() })
Thanks guys, simply I had to use name of the file dot name of the function and it worked. jsfile.setValue(#Model.ApprovedAmount);

MVC 5 - Would like to have page display if not logged in

I am using the following code to display a login form (Login.cshtml) when the user is not authenticated and the main page when the user is authenticated:
Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- META SECTION -->
<title>Coalesce</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<!-- END META SECTION -->
<!-- CSS INCLUDE -->
<link href="~/Content/Template/css/theme-default.css" rel="stylesheet" />
<!-- EOF CSS INCLUDE -->
</head>
<body>
#if (!Request.IsAuthenticated) {
<div class="login-container">
#RenderPage("~/views/Account/Login.cshtml")
</div>
RenderBody();
}
else {
...Normal page here
}
</body>
</html>
The Login.cshtml looks something like this:
<!DOCTYPE html>
<html lang="en">
<body>
...Login controls
</body>
</html>
I am using OWIN and everything wroks fine, but when I hit the login page portion, it only displays on half the screen, so half is the login page, and the bottom is white.
I've tried RenderPartial and a few other things in the authentication check, but I get get the login page to display on the full browser window.
I'm sure its the way that
#if (!Request.IsAuthenticated) {
#RenderPage("~/views/Account/Login.cshtml")
RenderBody();
}
is constructed, but i'm currently stumped.
I've never seen this approach before, but in any case (assuming it works) Login.cshtml should not contain <!DOCTYPE>, <html> and <body> tags because it will be rendered inside Layout.cshtml, which already contains these tags.
The approach that I am familiar with is: let a Controller, or even a global ActionFilter, check if one is logged in. If not, show View("Login"), or redirect to /Home/Login. Then let Login.cshtml be rendered using Layout.cshtml (which contains no login logic) - and not the other way around which is what you seem to be trying.
Controllers/HomeController.cs example
public ActionResult Index()
{
if (!Request.IsAuthenticated)
return View("Login");
// Add normal flow here
}

How to replace current layout at runtime?

I have a little app (asp.net mvc).
I have a question: in my project i have a layout - _layout.chtml,
It's possible to replace the content with different content that i inject from a file?
For example:
Current _layout.chtml:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
#RenderBody()
</body>
</html>
Now, i want to load new content from a file and replace the current _layout with new content as follows:
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
<link href="~/css/mycss.css" rel="stylesheet" />
</head>
<body>
#RenderPage("../Shared/_Header2.cshtml")
#RenderBody()
#RenderPage("../Shared/_Footer2.cshtml")
<script src="~/scripts/jquery.js"></script>
<script src="~/scripts/angular.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
How do i can to do that?
Thanks!
If you don't want overwrite your _ViewStart.cshtml you some other ways
return View ("NameOfView",masterName:"viewName");
Or
store your layout in viewData like
//in controller
ViewData["Layout"]="your layout path";
//in _ViewStart.cshtml
Layout = ViewData["Layout"];
Or you can create a custom attribiute and set your layout name in it like
[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
return View();
}
for more information check this answer specify different Layouts
I'll assume you're calling a new controller action at the time where you want to replace your layout. If so, then one of the following would do the trick;
First off you can put a _ViewStart.cshtml file in your \Views\ folder to override the default layout as seen below.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
From here you can add another _ViewStart.cshtml file in \Views\User to override the default layout for all your \User\ views.
#{
Layout = "~/Views/Shared/_UserLayout.cshtml";
}
You can also specify the above in a view, e.g. for \Views\User\Index.cshtml.
#{
Layout = "~/Views/Shared/_UserIndexLayout.cshtml";
}
Or you can specify the layout when returning the view in the controller;
return View("Index", "~/Views/Shared/_UserLayout.cshtml", someViewModel);

"Object reference not set to an object" when starting out with Cassette

I'm trying to get started with Cassette via NuGet. I'm having issues with it in my app so I rolled back and tried it in a new empty ASP.NET MVC 3 web application.
However, the problem persists. Following the documentation page "Easy to use", I simply can't get it to work. Here's the exception along with a bit of the stack:
"Object reference not set to an instance of an object."
[NullReferenceException: Object reference not set to an instance of an object.]
Cassette.CassetteApplicationContainer.get_Application() +6
Cassette.Views.Bundles.Reference(String assetPathOrBundlePathOrUrl, String pageLocation) +14
ASP._Page_Views_Shared__Layout_cshtml.Execute() in d:\Dave\Documents\Visual Studio 2010\Projects\CasetteTest\Views\Shared\_Layout.cshtml:2
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
I simply followed the two steps in the documentation and this is what I get. What am I doing wrong?
This is what my _Layout.cshtml file looks like:
#{
Bundles.Reference("Scripts/jquery-1.5.1.min.js");
Bundles.Reference("Scripts/modernizr-1.7.min.js");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body>
#RenderBody()
#Bundles.RenderScripts();
</body>
</html>
I figured it out.
I included the Cassette.Views package which does not create a default CassetteConfiguration.cs file that bundles each script and each css file in its own bundle. That's what triggered the NullReferenceException. In order to get it to work, you'll need to add the Cassette.Web package instead. In my defense, the package descriptions in the NuGet gallery are not clear and one is led to believe that the Views package is required for MVC and the other for WebForms.
The next problem was that I referenced the minified '.min.js' scripts which are not picked up by the bundler (it seems).
Cannot reproduce the issue.
4 simple steps allowed me to get a fully working prototype in less than 30 seconds:
Create a new ASP.NET MVC 3 project in Visual Studio
Install-Package Cassette.Web
Index.cshtml:
#using Cassette.Web
#{
Bundles.Reference("~/Scripts/jquery-1.5.1.js");
Bundles.Reference("~/Scripts/jquery-ui-1.8.11.js");
Bundles.Reference("~/Content/site.css");
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Web App</title>
#Bundles.RenderStylesheets()
</head>
<body>
<div>Hello World</div>
#Bundles.RenderScripts()
</body>
</html>
Hit Ctrl+F5 to run the project

Resources