How to add a new page in ASP.NET mvc4? - asp.net

I want to make a new project and I want to add a new page, using the Microsoft sample website as a starting point. The Microsoft sample website already has an About and a Contact page.
How do I add a new page to the sample website using ASP.NET mvc4?

In ASP.NET MVC you work with Models, Controllers and Views. Controllers are classes containing methods called Actions. Each Action is used as an entry point for a given user request. This Action will perform any necessary processing with the model and return a view. So basically you will start with defining a Controller (if not already done) and add Actions to it:
public class HomeController: Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction()
{
return View();
}
}
Then you right click on the Action name and select the Add->View option which will create a new View for the given Action in the respective ~/Views folder.
I would recommend that you start by going through the basic tutorials here: http://asp.net/mvc

Related

How to make Output cache for tweetsharp twitter feeds in asp net mvc5

I am using tweetsharp nuget package for adding tweets to my website.
I put my partialview on footer and it is visible on everpage of website.
here is my codes on Basecontroller.
public PartialViewResult _PartialView_twitter_feed()
{
var service = new TwitterService("key", "key");
service.AuthenticateWith("key", "key");
IEnumerable<TwitterStatus> tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName="my_screen_name", Count=5 });
ViewBag.Tweets = tweets;
return PartialView();
}
and I call it like this on footer view.
#Html.Action("_PartialView_twitter_feed", "base")
Now is the question, How can I make output caching or some kind of caching for this implementation on asp net mvc 5?
I dont want to call twitter api in every page view again and again. Because partial view is on footer.
How can I make it only once and show it until user leaves my website?
What can be the best practise to achive this?
Thanks for any help.
You can use OutputCache attribute. I hope the following example will help you.
Controller
[OutputCache(Duration = 6000)]
public PartialViewResult Footer()
{
return PartialView("Footer");
}
public ActionResult MainPage1()
{
return View();
}
public ActionResult MainPage2()
{
return View();
}
View
MainPage1
<h2>MainPage1</h2>
#Html.Action("Footer")
MainPage2
<h2>MainPage2</h2>
#Html.Action("Footer")
When user access the MainPage1 first time, the Footer partial view will return from server. From second time onwards it will return from cache. Even when user access MainPage2 the footer partial view will return from cache. You can increase the duration seconds based on your requirement

ASP.Net - how to have multiple submit buttons and also submit the form via javascript?

I'm new to ASP.Net and am trying to make a web application using MVC2.
On one particular page I need to have multiple submit buttons - after reading up from this post I found this method which worked well in my project.
So I have a few submit buttons handled in my controller like this:
[HttpPost]
[MultiButton(Key = "action", Value = "Button1")]
public ActionResult Action1(MyViewModel myViewModel)
{ //do stuff
return View(newViewModel)
}
[HttpPost]
[MultiButton(Key = "action", Value = "Button2")]
public ActionResult Action2(MyViewModel myViewModel)
My problem is that now I want to also postback my form on various client events. I tried to do this in the view by using javascript in there somewhere.
<% using (Html.BeginForm("Index", "MyController")){ %>
document.forms["form1"].submit();
With a 'normal' action on the controller:
[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
}
But when I add this, now the multiple submit buttons do not work properly due to an ambiguous match exception between Action1 and Index. I realise that they have the same signature but as a beginner, I'm a bit stuck at this point!
What can I do to get all the different submit options working together? Please advise and/or point out where I'm going wrong. Thanks

Create controller for partial view in ASP.NET MVC

How can I create an individual controller and model for a partial view? I want to be able to place this partial view any where on the site so it needs it's own controller. I am current rendering the partial as so
#Html.Partial("_Testimonials")
Why not use Html.RenderAction()?
Then you could put the following into any controller (even creating a new controller for it):
[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
var model = repository.GetThingByParameter(parameter1);
var partialViewModel = new PartialViewModel(model);
return PartialView(partialViewModel);
}
Then you could create a new partial view and have your PartialViewModel be what it inherits from.
For Razor, the code block in the view would look like this:
#{ Html.RenderAction("Index", "Home"); }
For the WebFormsViewEngine, it would look like this:
<% Html.RenderAction("Index", "Home"); %>
It does not need its own controller. You can use
#Html.Partial("../ControllerName/_Testimonials.cshtml")
This allows you to render the partial from any page. Just make sure the relative path is correct.
If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:
// Assuming the controller is named NewController
#{Html.RenderAction("ActionName",
"New",
new { routeValueOne = "SomeValue" });
}
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async
#await Html.PartialAsync("_LoginPartial")
or
#{await Html.RenderPartialAsync("PartialName");}
or if you are using .net core 2.1 > you can just use:
<partial name="Shared/_ProductPartial.cshtml"
for="Product" />
Html.Action is a poorly designed technology.
Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.
To be closer to WebForm UserControl (*.ascx) you need to:
Create a page Model and a Partial Model
Place your Partial Model as a property in your page Model
In page's View use Html.EditorFor(m => m.MyPartialModel)
Create an appropriate Partial View
Create a class very similar to that Child Action Controller described here in answers many times. But it will be just a class (inherited from Object rather than from Controller). Let's name it as MyControllerPartial. MyControllerPartial will know only about Partial Model.
Use your MyControllerPartial in your page controller. Pass model.MyPartialModel to MyControllerPartial
Take care about proper prefix in your MyControllerPartial. Fox example: ModelState.AddError("MyPartialModel." + "SomeFieldName", "Error")
In MyControllerPartial you can make validation and implement other logics related to this Partial Model
In this situation you can use it like:
public class MyController : Controller
{
....
public MyController()
{
MyChildController = new MyControllerPartial(this.ViewData);
}
[HttpPost]
public ActionResult Index(MyPageViewModel model)
{
...
int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
...
}
}
P.S.
In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see ASP.NET MVC partial views: input name prefixes

How to use ASP.Net -- Html.ActionLink()

Okay, I'm pretty new to ASP.Net / MVC 2. Can anyone explain how to use the Html.ActionLink thing? I understand that the first parameter is the displayed text, but for the second one, what is the action name??
User action in the asp.net MVC framework is based around Controllers and Actions that enable you to create pages (or links) to specific sections.
For example you might want a page to edit a Product so you have a Product Controller with an Edit Action. You can then create a Html ActionLink that will direct the user to this page.
In summary the 'action' will be the ActionResult method you want to direct your user to.
<%: Html.ActionLink("Edit Product", "Edit", "Product") %>
public class ProductController : Controller
{
public ActionResult Index() // Index is your action name
{
}
public ActionResult Edit(int id) // Edit your product
{
}
}

asp mvc controller creation

i want dynamically create ascx files, to partial render them.
but as i know, ot show them , i at least need dummy method:
public ActionResult test()
{
return PartialView();
}
how can i create this method for each new ascx file?
upd: i need factory?
Why would you create dynamic ascx files?
If you want to create all the layout in the controller you should be able to return it directly.
But then, why would you do that?
This way it will be really hard to do unit testing and refactoring and reuse.
You'd need to create your .ascx controls ahead of time. If you are doing this, I would recommend that you register a new view engine to provide a new PartialView location.
public class MyViewEngine : WebFormsViewEngine
{
public MyViewEngine()
{
PartialViewLocationFormats = new[]
{
"~/Views/{1}/{0}.ascx",
"~/Views/GeneratedControls/{0}.ascx",
"~/Views/Shared/{0}.ascx"
};
}
}
This allows you to write your dynamic views to the /Views/GeneratedControls/ folder. If you need to use a specifically named control (i.e. the control you generate has a random name) then you simply need to adjust your call to PartialView:
public ActionResult test()
{
return PartialView("name-of-control");
}
Otherwise MVC will use the name of the Action as the name of the control to use.

Resources