Do we have user control and hidden field in razor? - asp.net-mvc

In Asp.net , there is user control, which is an ascx page, and we can have hidden fields:
public partial class classA:System.Web.Mvc.ViewUserControl<Models.classB>
{
//hidden field
public string url
{
get{ ...... }
}
}
But now i am using razor in asp.net mvc3 ,which is cshtml file. Do we have anything corresponding to that? How can i use hidden field now?

MVC views do no have fields like a Web Forms user control.
MVC views (partial views, too) get their data by passing an instance of a Viewmodel class to them. You can indicate the type of the viewmodel class with the #model directive (usually the first line in a view):
#model MyViewmodelClass
<span>#Model.MyClassProperty</span>
The viewmodel class itself could contain private fields like any class.
If you need variables to be used within the view itself, you can simply declare them within a razor code block and use them wwithin the view:
#{
var privatevar = "value";
}
<span>#privatevar</span>
However, as a best practice, the view's responsibility in ASP.NET MVC should be limited to the display of the data and therefore not contain code unrelated to that.

While working with razor it is essential to have basic HTML knowledge as you need to write some html and there is no and Drag and Drop to add controls on the page.
MVC have introduced Partial Views which can be said a alternate/replacement to User Control.
You can create a PartialView by selecting Checkbox stating "Create Partial View" in View Creation Dialog. Secondly In MVC it is not difficult to create partial view mannual as well.
As you are using Razor, just set Layout = null; at the top of your view and it will be treated as partial view. Secondly you can easily make any field as hidden using display property under Style attribute.
Happy Coding :)

Related

Asp.net MVC way to pass data to _layout.cshtml?

I keep reading that the MVC way to pass data from a controller to the view is done via a ViewModel, but what about passing data to _Layout.cshtml, like page title, meta description, article author, etc...
What's the MVC way to pass this kind of data? Should I just use ViewBag for them?
You have few ways:
ViewBag
ViewData
View Components
Injections (example below)
ViewBag and ViewData are quite easy to use, however not always convenient.
There is one big plus - you could set/read them in one place of view and read in another - for example, you could set them in your main view and read/display them in _lauout.cshtml.
View Components are the most interesting new feature in MVC Core (in my opinion) which allows you to create UI widgets.
There is a little bit more coding for ViewComponent (you need to create controller and view), but it's flexible feature (I like it) and easy to call in a place where you need it, just
#await Component.InvokeAsync("NameOfCOmponent").
Injections not my favorite, but sometime usfull - for example if you want display user name, you could just put the following code directly into your layout/view file:
#using System.Security.Claims
#using Microsoft.AspNetCore.Identity
#inject UserManager<ApplicationUser> userManager
#{
var userInfo = ((await userManager?.GetUserAsync(User))?.xxx);
// where 'xxx' is any property of ApplicationUser model
}
then you can use #userInfo in the same view to display that info.
More information:
Views Overview
Passing Data to Views
View Components

ASP.Net MVC Partial View Model Binding

I'm very new to MVC and I am looking to put a list of links on the main layout(master page) based on database table. I'm sure I read before that you shouldn't try to load models on the master page but use Partial Views instead (correct me if I'm wrong).
I've looked on Google and on other questions here but they only seem to talk about passing data from a main view to a partial view via ViewBag but I think I just want to add a partial view that I can add to the master page.
Can someone please tell me how to create a partial view I can add to master page so its used on every page and be able to load the list of links required i.e. by binding IEnumerable model to Partial View?
Try using ChildActionExtensions.Action
In your layout:
#Html.Action("MyAction", "MyController")
Controller:
public ActionResult MyAction()
{
var list = // get your list values
return PartialView("MyViewName", list);
}
Then just create your partial view:
#model IEnumerable<WhateverType>
#* View goodness *#
You can use this to bind whatever model you need to your partial view and if you use the Action helper in your Layout.cshtml it'll be rendered on every page.

Partial content accepting HTML as parameter in ASP.NET MVC 3

I have a concept of a modal window in my MVC application that renders some HTML that wraps content that will eventually show inside on the modal. The content will be HTML either directly hard coded in the view or generated by an Html helper as passed in as a parameter.
I'd like to wrap the modal content in a Razor template or partial in my application to avoid spreading it all over my application as it used in a number of pages. What's the easiest way of doing this? Can I achieve something similar in i partial view with out a model?
Build a viewmodel for the partial view... a simple C# class with a string property for the Html... using the [AllowHtml] attribute on it will let you stuff HTML in the object.
In your parent view, stuff your HTML into this view model and pass it to the partial when you call it.

VB.NET : How to write to a PlaceHolder in MVC

I am new to MVC.
I have a string that I built from a controller called parsedCustomerNames. In web forms I can make the placeholder visible from the codebehind and then populate a control with the string.
How would I be able to do this in MVC.
I believe parsedCustomerNames is a coma separated list of customers (As opposed to a collection). You can do it like this in ASP.NET MVC:
Suppose, following is your controller:
public class HomeController : Conroller{
public ActionResult Index(){
ViewData["ParsedCustomerNames"] = parsedCustomerNames; //Get the string here.
return View();
}
}
And then inside your view, do the following:
<div class="customerName">
<%: ViewData["ParsedCustomerNames"] as string %>
</div>
Here you don't need placeholder as such.
Place this logic of showing this string inside a "Div". If you have anything in string, div will appear otherwise it will be as good as invisible.
Another thing to focus is that Asp.Net MVC is not event driven as normal Asp.Net is. You need to think in terms of Get and Post. Everything you do in Asp.Net MVC will be a result of user action which will be Get/Post. Every action will provide some data (M of MVC) to your view and you will have to redraw your page (v of MVC). If you have any data on particular "div" then it will appear automatically otherwise not.

Function in ASP.NET MVC

A function returns only one view.
what if I want to return multiple views in a function?
For example, I have this code:
Function Index() As ActionResult
Dim _news As DataTable = News.newsSelect()
Dim _announcement As DataTable = Announcement.SelectAnnouncement()
Return View()
End Function
I want to return _news and _announcement to be used in the aspx page. How would I do this?
Are you trying to show both sets at the same time? News and Announcements?
If so then why not implement either a PartialView or two PartialViews?
Then in your main view you can render them and pass the collection to the PartialViews?
There are heaps of samples on this and the one I recommend is in NerdDinner if you haven't already seen it.
I hope this helps. If you want sample code then let me know.
One simple way is just to have those two datasets sent in a ViewData element, which you can access in a field.
example:
ViewData["Elements"] = new SelectList(aElements, "Guid", "Name");
is consumed as:
<%= Html.DropDownList("Elements","Pick an element")%>
Also, I think that if you read between the lines of this blog post here you will find an elegant way of achieving what you want ;) but its a bit more involved..(only because you mentioned Views instead of just variables..
Quote:
We need to create our own implementation of IViewFactory. This
is responsible for locating and
creating an instance of an IView
(which both ViewPage and
ViewUserControl implement).
To “inject” (all you DI fans excuse me borrowing the term without
using a DI framework) our new View
Factory into every Controller we are
going to create our own
IControllerFactory implementation.
We need to configure the framework to use our new Controller
Factory.
Finally we can create two Views – an AJAX version and a pure
HTML version.
Building on that should be all you need
Good luck!
Ric
Assuming what you are trying to do is use both of those DataTables to populate some View, then my recommendation would be to create a wrapper object and then a strongly typed view based on this object.
The wrapper object would contain properties for all of the data elements that you need in order to render your view properly. In your case, it is 2 DataTable objects. I do not really know VB, so all my examples will be in C#. Here is an example of the data wrapper class...
public class IndexViewData
{
public DataTable News { get; set; }
public DataTable Announcement { get; set; }
}
You then might update the Index action in your controller as follows:
public ActionResult Index()
{
var viewData = new IndexViewData();
viewData.News = News.newsSelect();
viewData.Announcement = Announcement.SelectAnouncement();
return View(viewData);
}
Finally, you would need to create/update your view to be strongly typed. This is done by having your page inherit from the generic System.Web.Mvc.ViewPage<T> class. Just substitute the view data wrapper created earlier for T. To do this, you would set the inherits attribute of the <%# Page %> element. In your case, if we assume your root namespace is called "Foo", you might have the following page declaration in your Index.aspx view (added extra line breaks for readability):
<%# Page Title=""
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Foo.Models.MyModelType.IndexViewData>"
%>
Once you have a strongly typed view for your view data wrapper, you can access the wrapper object in your view using the Model property. Here is an example of something you could do in your Index.aspx view
<%-- Output some random data (bad example, for demonstration only) --%>
<%= Model.News[0]["title"] %><br/>
<%= Model.Anouncement[0]["body"] %>
In reality you're probably going to do something like iterate over each row of the data table. Regardless, once you create the strongly typed view, your model object, which was passed to the view in the Index method of the controller, is available in the Model property within the view.
You can find detailed tutorials at the ASP.NET MVC site

Resources