How to add code to an MVC cshtml file view - c#

really new to MVC and not sure how i would get my variable 'UsersFullName' from the code behind class file to the view. With aspx and aspx.cs i would have done this:
index.aspx.cs:
using System.DirectoryServices.AccountManagement;
namespace TeamRequestForm.Controllers
{
public class AddTeamController : Controller
{
// GET: AddTeam
public ActionResult Index()
{
return View();
}
private string usersFullName = UserPrincipal.Current.DisplayName;
public string UsersFullName { get { return usersFullName; } }
}
}
index.aspx:
<input type="text" value="<%=UsersFullName%>" name="changeOriginator" id="changeOriginator">
How can I do the same in a view? Many thanks in advance.

Create a Model:
public class UserModel
{
public string FullName { get; set; }
// Any other properties
}
And return it to your view:
public ActionResult Index()
{
var viewModel = new UserModel { FullName = // Logic for set };
return View(viewModel);
}
And then in your view, declare this at the top of your view:
#model namespace.UserModel
And in the input you can reference this model by using #model.FullName or, even better:
#Html.EditorFor(model => model.FullName)

Viewbag is one way to do it. Adding it to your model is another. There are more options. Have a look at these articles
http://www.c-sharpcorner.com/uploadfile/abhikumarvatsa/various-ways-to-pass-data-from-controller-to-view-in-mvc/
http://www.webdevelopmenthelp.net/2014/06/asp-net-mvc-pass-data-controller-view.html

public ActionResult Index()
{
ViewBag.UsersFullName = UsersFullName;
return View();
}
View
#Html.TextBoxFor(c => c.UsersFullName )
check out the MVC documentation on StackOverflow

You can do this from many ways, but these are most popular approaches:
1) using ViewBag
public ActionResult Index()
{
private string usersFullName = UserPrincipal.Current.DisplayName;
ViewBag.userFullName=usersFullName;
return View();
}
and call this ViewBag at your .cshtml page
like below:
<span>#ViewBag.userFullName</span>
2) using ModelView
For ViewModel approach you have to create Properties for your Entities in class like below:
public class UserViewModel
{
public string userFullName{get; set;}
}
and use this ViewModel into your Controller like this
public ActionResult Index()
{
private string usersFullName = UserPrincipal.Current.DisplayName;
UserViewModel objCls=new UserViewModel();
objCls.userFullName=usersFullName;
return View(objCls);
}
and use on .cshtml page like below:
#model UserViewModel //your class refrence
<span>#Model.userFullName</span> // you will get your value here
Hope it will helps you. Thanks

Related

How to save object to session in ASP.NET & access it in View

I am writing Asp.Net MVC 4 application. I want to save model object to session and then access it from another page but don't know how to do it. Is it possible? For example some code:
[HttpPost]
public ActionResult Index(EventDetails obj)
{
if (ModelState.IsValid)
{
Session["EventDetails"] = obj;
return RedirectToAction("Index2","Home");
}
else return View();
Here Event details model code:
namespace ProjectMVC.Models
{
public class EventDetails
{
[Required]
public string FirstTeamName { get; set; }
}
}
So I want to save EventDetails object to session and then access it in View like a normal object. Something like this:
#Session["EventDetails"].FirstTeamName
You need to bind it to a ViewModel:
var vm = (EventDetails)Session["EventDetails"];
return View(vm);
In your view you simply:
#model EventDetails
#Model.FirstTeamName

Accessing model properties in Razor-4 view

I have the following EF generated data model:
public partial class PrinterMapping
{
public string MTPrinterID { get; set; }
public string NTPrinterID { get; set; }
public string Active { get; set; }
}
I then have the following view model:
public class PrinterViewModel
{
public PrinterMapping PrinterMapping;
public Exceptions Exceptions;
public IEnumerable<PrinterMapping> Printers;
}
In my Index Action in HomeController I am passing my view model to the Index view.
private eFormsEntities db = new eFormsEntities();
public ActionResult Index()
{
PrinterViewModel printerModel = new PrinterViewModel();
printerModel.Printers = from pt in db.PrinterMapping select pt;
return View(printerModel);
}
My Index view is calling a partial view in the following manner towards the end (probably wrong):
#Html.Partial("~/Views/Home/GridView.cshtml")
My GridView.cshtml looks like:
#model AccessPrinterMapping.Models.PrinterViewModel
<h2> This is Where the Grid Will Show</h2>
#{
new WebGrid(#model.Printers, "");
}
#grid.GetHtml()
I learned about the WebGrid method from http://msdn.microsoft.com/en-us/magazine/hh288075.aspx.
My WebGrid line isn't happy at all since it doesn't recognize #model within that line.
How do I access the Printers in the view model that I passed in? Is this even possible?
Thanks very much to you all.
Theres two issues with your code.
First, you should explicitly pass your model in like this:
#Html.Partial("~/Views/Home/GridView.cshtml", Model) #* explicitly pass the model in *#
Then, because you are already in a code block in your partial view.. you don't need the # symbol.. and Model has an uppercase M.
new WebGrid(Model.Printers, "");
#model is a directive for your views/partial views. Think of it as a "configuration" command. Model is an actual property. It is the object that is passed into the view.. and is of the type you specified with the #model directive.
#{
new WebGrid(Model.Printers, "");
}
and also you have to pass your model into partial view in
#Html.Partial("~/Views/Home/GridView.cshtml")
in second parameter. I guess this call should be
#Html.Partial("~/Views/Home/GridView.cshtml", Model)

Do you always have to set ViewBag variables in order to access data from the controller

I have a controller like this:
public ActionResult Index()
{
ViewBag.Title = "Index";
ViewBag.LoggedIn = TheUser.CheckStatus();
return View();
}
Thing is, I have to set LoggedIn to the output of my other function TheUser.CheckStatus() so that I can reference it with razor... Is there a way in Razor to access a function straight off? for example...
#TheUser.CheckStatus
instead of
#ViewBag.LoggedIn
The recommended way in MVC for passing information to a view is to create a model specific to that view (aka view model) e.g.
public class IndexViewModel
{
public string Title { get; set; }
public bool IsAuthenticated { get; set; }
}
....
public ActionResult Index()
{
return View(new IndexViewModel()
{
Title = "Index",
IsAuthenticated = UserIsLoggedIn()
});
}
However, to answer your question:
Is there a way in Razor to access a function straight off?
If you are using ASP.NET Membership you can use the IsAuthenticated property on the request e.g.
#Request.IsAuthenticated
Otherwise, you do need to pass this information to the view (whether that be via ViewBag/view model etc.)
Alternatively, you could write your own extension method for Request which would allow you to access it directly in the view:
#Request.UserLoggedIn()
Or even as a HtmlHelper e.g.
public static class HtmlHelperExtensions
{
public static bool UserIsLoggedIn(this HtmlHelper helper)
{
return /* authentication code here */
}
}
Then in your views you can use #Html.UserIsLoggedIn() which I think is what you are after.
use a ViewModel class (your view will then be strongly typed, and you'll be able to use "classic" helpers).
//viewModel class
public class UserStatusViewModel {
public string Title {get;set;}
public bool IsLogged {get;set;
}
//action
public ActionResult Index() {
var model = new UserStatusViewModel{ Title = "Index", IsLogged = TheUser.CheckStatus()};
return View(model);
}
//view
#model UserStatusViewModel
#Html.DisplayFor(m => m.Title)
#Html.DisplayFor(m => m.IsLoggedIn)

Default ModelBinder not working properly

I have this following structure:
public class Dummy
{
public string Name { get; set; }
public InnerDummy Dum { get; set; }
}
public class InnerDummy
{
public string Name { get; set; }
}
And an ActionResult that receives a Dummy
[HttpPost]
public ActionResult Index(Dummy dum)
{
var dsad = dum;
//var dwss = idum;
return RedirectToAction("index");
}
On my view I have:
#model TestMVC3Razor.Controllers.HomeController.Dummy
#using (Html.BeginForm())
{
#Html.TextBoxFor(o => o.Name)
#Html.EditorFor(o => o.Dum)
<br />
<br />
<input type="submit" />
}
It is posting
Name=xxx
Dum.Name=yyy
But when I try to get dum.Dum.Name on the ActionResult I get null instead of yyy. Is this a bug or just the way it is? Am I not using it right? Do I need to implement a new binder for this?
HI~ your view should use #Html.EditorFor(o => o.Dum.Name)
not #Html.EditorFor(o => o.Dum)
And postback Controller:
[HttpPost]
public ActionResult Index(Dummy postback)
{
var dsad = postback;
var a = postback.Name; //get Name of Dummy
var b = postback.Dum.Name; //get Name of InnerDummy of Dummy
return RedirectToAction("index");
}
If you have problems about it, please let me know :)
You need to pull the InnerDummy out from inside the Dummy class.
When the default model binder finds the Dum property it will try to create an object of type InnerDummy, but in its context that doesn't exist. To reference InnerDummy as you have it the model binder would need to create a Dummy.InnerDummy, but it has no way of knowing that.
Making InnerDummy a direct member of the namespace will fix the problem.
It may also be possible to fix the problem by declaring Dum as:
public Dummy.InnerDummy Dum { get; set; }
I'm not sure about this, though.

asp.net mvc2 - how to get model and model.something in the same way in controller?

If my Model is Contacts then I can easily get it in controller like this:
[HttpPost]
public ActionResult Create(Contact contact)
...
But if my Model is wrapper for Contacts and something else then in View I display it using Model.contact.
How to get Contact in Controller the same way like I did in first case? I don't want to use Formcollection.
If you want to bind only the Contact but it is not the Model of your view but it is part of it as you have written, you can do the following for create:
[HttpPost]
public ActionResult Create([Bind(Prefix = "Contact")]Contact contact)
And for the edit you can do the same, and you need to specify also in UpdateModel the prefix, like this:
[HttpPost]
public ActionResult Edit([Bind(Prefix = "Contact")]Contact contact){
UpdateModel(contact, "Contact");
}
For example you have
public class MyViewModel
{
Contact MyContact { get; set; }
Object SomethingElse { get; set; }
}
You can get it back by using the same type object as parameter:
[HttpPost]
public ActionResult Create(MyViewModel returnedModel)
{
Contact returnedContact = returnedModel.MyContact;
// ...
}

Categories