Avoiding .NET MVC controller calls with angular-ui-router - c#

I am building a .NET MVC 5 application on back-end and Angularjs on front-end.
I am loading .cshtml views in a div containerOne on a parent .cshtml page with ui.router and everything is working fine. An issue I would like to solve is when I enter manually a page URL that is C# controller's action path(in the example I provided below it is /Proposal/Customers) - my view is loaded on a whole page. What I want to be called is a .state named 'customers' in my example, or something like that. My example code is(part of my proposalConfig.js):
.state('customers', {   
url: 'AllCustomers',
views: {
containerOne": {
templateUrl: '/Proposal/Customers'
}
}
});
On my back-end I have a ProposalController.cs and an action method Customers that calls a Customers.cshtml view.
Anyone has an idea how to solve this?
EDIT
The same thing happens if, instead of 'AllCustomers' I put '/Proposal/Customers', and then after the first load of a .state I refresh a page.
I forgot to mention that I have $locationProvider.hashPrefix('!').html5Mode(true); in a proposalConfig.js file.

If you mean that the entire page html markup (html tag, body tag and such)is being returned when you only want the specific content of the Customer.cshtml, which I also assume only has what you want in it, its probably because your view has a shared view start layout. Put this in Customer.cshtml
#{
Layout = null ;
}

Related

ASP.NET Core 6 How to redirect from one view to other

tl:dr:
I would love to redirect from my Layout view into an index view of a certain class. I do not want to do it through a button.
After I log in the layout page changes depending on your role. If you have a regular user role I want you to be immediately redirected to another view.
This the part of the code where I would like the redirecting to take place. In the "else" clause.
Is there a simple way about please?
I was thinkig of calling a method from a controller of said class which would simply have the redirect method inside. But that has failed since I was not able to call such method simply in a view and I failed to find a way after a long google search.
Thank you for your help.
According to your description, if you want to redirect the view from layout to another view, I suggest you could consider using the Context.Response.Redirect("~/Account/LogIn");
More details ,you could refer to below example:
#if (Context.User.Identity.IsAuthenticated)
{
}else
{
Context.Response.Redirect("/home/Privacy");
}

Static HTML page in ASP.NET MVC that does not use Layout

I have an entire Web Application built using ASP.NET MVC and have a _ViewStart.cshtml page that specifies a Layout.
This works great for my entire site. However, I have a single prototype static HTML page that I just need to dump into a directory.
I copied the HTML into a CSHTML file and fronted it with a controller. The problem is that when I go to this page, it is using the Layout.
How can I configure it so that I can just serve this page up as static, standalone content without the Layout from _ViewStart?
By default, all views will use the layout from ~/Views/Shared as it is specified in the _Viewstart.cshtml file. Every time a view is executed, the code inside the _Viewstart.cshtml will be executed which sets the layout for the view.
If you do not want to execute/include the layout for a specific view, you can explicitly set layout as null on a view. Add the below code to the view.
#{
Layout = null;
}
Keep in mind that, even though it is static html in your cshtml file, user will not/should not directly access this view (like a normal html page/htm page). It has to be routed via an action method which returns this cshtml view.
Another option is to use the PartialView method instead of View method. When using the PartialView method to render a view, the framework do not run _ViewStart.cshtml, hence you get the same result.
public ActionResult About()
{
return PartialView();
}
PartialView is really handy when you want to render the markup for parts of your page (Ex : content of for a modal dialog etc)
In your static view page set layout = null.
Like:
#{Layout = null;}

How can I respond to events on a page in an ASP.NET MVC app that need to access data within the View?

In my ASP.NET MVC project, I need to dynamically manipulate some html elements when the user makes a couple of selections. I assume this needs to be done in code-behind C# (as opposed to in jquery), because how I respond is using data that is retrieved from a SQL Server database and is part of the View (I don't think jQuery would/could know about this MVC/.NET-specific data).
Specifically, when a user clicks a checkbox on the page, provided a selection has been made from an html-select element, my code needs to spring into action to populate other elements on the page.
The View (.cshtml) is getting the data in a Razor code block like so:
#model WebAppRptScheduler.Models.HomeModel
#using System.Data
#{
DataTable dtUnitReportPairEmailVals = Model.UnitReportPairEmailVals DataTable;
var unitRptPairEmailVals = from x in dtUnitReportPairEmailVals.AsEnumerable()
select new
{
emailAddr = x.Field<string>("EmailAddr")
};
This data comes from the Controller:
DataTable UnitReportPairEmailValsDT = new DataTable();
UnitReportPairEmailValsDT = SQL.ExecuteSQLReturnDataTable(SQL.UnitReportPairEmailQuery, CommandType.Text, null);
model.UnitReportPairEmailVals = UnitReportPairEmailValsDT;
Does this (event handling) code belong in the Controller? If so, how is the method declared/decorated so that there is a connection between it and the html elements whose events it needs to monitor?
This is what needs to happen:
User selects an option from an html select
User clicks a checkbox
The code determines that both an option has been selected, and a checkbox checked; it then uses the data to populate other controls, something like this:
#if (unitRptPairEmailVals.Count > 0)
{
email1.Text = unitRptPairEmailVals[0];
}
#if (unitRptPairEmailVals.Count > 1)
{
email2.Text = unitRptPairEmailVals[1];
}
#if (unitRptPairEmailVals.Count > 2)
{
email3.Text = unitRptPairEmailVals[2];
}
The above would populate the text/value of these html inputs:
<label class="margin4horizontal">Email 1</label><input type="text" name="email1" id="email1" />
<label class="margin4horizontal">Email 2</label><input type="text" name="email2" id="email2" />
<label class="margin4horizontal">Email 3</label><input type="text" name="email3" id="email3" />
BTW, if I'm barking up the wrong tree, or am even in the wrong forest altogether, please let me know what the preferred approach is.
UPDATE
Once I pieced together several different answers to this and related questions, I wrote up a tip on how to do this here.
Update: I was answering on mobile last night, and here is a clearer edit and some sample code...
Asp.net MVC has controllers, which contain actions. When you navigation to a URL (HTTP GET), ASP.net translates this via routes into a specific controller action to invoke, then the result of that action is sent back to the browser as plain HTML.
Also when you submit a form (HTTP POST) to specific URL it translates to invoking a controller action via routes. and a ModelBinder will read the body of that HTTP POST and converts it into your Model class. Unlike the classic web forms that used ViewState to track page controls, state, and events.
What you want to achieve can be done in 2 different ways...
Using JavaScript and JQuery. You can issue an Ajax request (GET, POST, etc) to a URL that exists in your ASP.net MVC routes table to execute an action and the results will be returned back to your JavaScript without navigating to another page.
Posting an HTML Form back to the server will allow ASP.net MVC to read the new/changed values in your HTML controls and pass those new values to the controller action, which in turn can render the same view again with the new values and behaviour.

How to update part of a cshtml shared layout on intervals?

I want to modify the content of a div in my shared layout when there is an update at my database. Whats the best way to go about it ? Timers to check database + somehow update view from controller ? In view c# functions ? ajax ?(don't know much about it) or some other way ? Thanks in advance.
Use setTimeout utility of javascript to get timer behavior.
Create a Controller Action and its associated partial view which will have the content you need to load dynamically. You can return a formatted Html from the view or a structured Json object from the controller action whichever is suitable for you..
considering that your following is your DIV tag.
<div id="dynamicContent"></div>
use
$(function(){
var function updatecontent()
{
$("#dynamicContent").load(URL)
setTimeout(updatecontent,5000);
}
setTimeout(updatecontent,5000);
});
to load content dynamically, url would be
YourDomain.com/Controller/Action
$.load()
will load the content of partial view using Ajax, and you will get a nice behavior on page.

What's the best place to put default content in an MVC application?

I'm working on a sort of a CMS/Wiki application to help me experiment with the new Asp.Net MVC framework, and I'm trying to wrap my head around some of the code organization.
Right now, I have three views that cover displaying an article: Index, Edit, and Rename. All three views display the contents of the current page, or placeholder content stating that the page does not exist.
This is currently accomplished with the following code in the action method for each view:
MyPage myPage = null;
if (!string.IsNullOrEmpty(pageName)) {
myPage = mRepository.GetMyPage(pageName);
}
//Page does not exist.
if (myPage != null) {
ViewData["pageContent"] = myPage.GetParsedSource(new PageState());
ViewData["pageSource"] = myPage.Source;
ViewData["title"] = myPage.Title;
}
else {
ViewData["title"] = pageName;
ViewData["pageContent"] = "Page does not exist, feel free to create it!";
ViewData["pageSource"] = "";
}
ViewData["pageName"] = pageName;
My question is, where should this logic actually go?
1) The Controller (as it is now), which requires the above code to be replicated across action methods?
2) The Model, defaulting values for pageSource to the verbiage shown above? This would have the downside of moving display text into the model.
3) The View, using a null coalescing operator to convert null ViewData entries to their defaults?
4) In the Views, but add additional controllers to handle cases where the pageName does not exist.
EDIT:
Hopefully this should clarify things a little. The flow of the application is as follows:
When the user enters a URL (i.e. /pages/page_title), they arrive at a screen which displays the content of the article, along with hyperlinks labeled "edit" and "rename."
Clicking edit displays a page which contains the article content, as well as form controls to edit the article's source.
Clicking rename displays a page which contains the article content, as well as form controls to edit the article's name.
I would have several actions:
Lookup
Display
Create
Edit
Rename
In your default Lookup controller action (which gets hit when the user asks for, say, "/wiki/article-title"), you can redirect (RedirectToAction()) to the appropriate action as necessary. That encapsulates your Create logic into its own controller, and can also be called directly (RESTful). Same with the others. That also allows you to keep your views very, very stupid (always a good thing).
I would keep it in the controller but extract it out so that you don't have to replicate the code in each of the actions.
Maybe set some defaults in the controller's constructor and then have a separate private method (ie. not an action method) that takes your MyPage object and sets the viewdata that is shared between your actions.

Categories

Resources