Accessing controls in Razor view from controller MVC4 - asp.net-mvc-4

I am new to MVC. In my application the view page created using razor by designing it from another html page designer. I have doubt that how to access the html controls from the corresponding controller. For example, i create a controller named Home and and corresponding view. Added a text box into it.
<input id="name" type="text" name="txtName"/>
Now i want to get and set the value in text box from controller without using script.
Just like
txtName.text="...."
Is that possible..?

It sounds like you are thinking of things from a Web Forms perspective, e.g. controls, setting properties server-side.
MVC allows much better separation of concerns, that is, each piece should play its part without being tightly coupled to other parts. Having a controller set a property of a textbox in a view means that there must always be a textbox in that view and would tightly couple the controller to that particular view. It is not directly possible and it would be a bad idea even if it was.
That's where view models come in:
// M - model
public sealed class MyViewModel
{
public string Name { get; set; }
}
// V - view
#model MyViewModel
// (usually code to begin a form goes here)
#Html.TextBoxFor( o => o.Name )
// C - controller
public ActionResult MyActionMethod()
{
var model = new MyViewModel { Name = "Hello" };
return View( model );
}
It may seem like an extra step (it is) but it is cleaner, far more flexible, and far more test-friendly.

It would only be possible with another request to the server (e.g. POST, GET) because the Controller code can only run server-side. After processing another request, you could use a ViewModel to populate your HTML text-box while rendering it, but I doubt that is what you are looking for.
If you are familiar with desktop programming (e.g. Window's Forms) and you are looking to immediately change and process fields on an HTML page, you will need to use JavaScript. If you are unfamiliar with web-programming, or even just new to the MVC paradigm, I suggest you try out a few MSDN tutorials.

Related

asp.net MVC - #HTML.Raw writes out model to page

I have an ASP.net MVC 4 (Razor) application. We are using Dojo's 1.9 Gridx to display data.
My controller returns my model to the view. To work with the model on the client side, I usually will assign it to javascript variable as so:
var _model = #Html.Raw(Json.Encode(Model));
I can then pass the _model to Dojo's Gridx control. What I don't like is if you view the source in a browser, the data in _model is visible on the page. Is seeing the _model data in the browser by design? or is there a better way to do this?
Another way to do it (not sure if it's better), is to send your model to your view via the standard #model MyModel, serialize it to JSON and set it as a value of an input element, and then grab the value of the input via Javascript. Then you can destroy/remove the input element, and that data won't be visible in the browser source anymore.
Example:
In Razor View
#model MyModel
<input type="hidden" id="myViewModel" value="#Newtonsoft.Json.JsonConvert.SerializeObject(Model)" />
In Your Javascrip File
$(function(){
var _model = JSON.parse($('#myViewModel').val());
$('#myViewModel').remove();
});
Doing it your way or this way, the entirety of the model's data will still be in the page's source (and hence visible to anyone looking) - even if it's for a short amount of time. Always remember that when considering security for your application.

In Orchard how do I render the editor for a ContentType on a cshtml page inside my module

I have a contentType defined, along with a driver + handler, it works fine inside of the admin page but I want to render the editor for a contentType on a cshtml page inside my module. How do I do this and can I still get the benefit of the parts being persisted etc.
You can use IContentManager.BuildEditor(...) to produce the editor shape for a content item, and render it in your view using #Display(Model.Whatever).
To deal with updates, you can also use IContentManager.UpdateEditor(...), passing in an implementor of IUpdateModel.
IUpdateModel is just an Orchardy way of abstracting calls to TryUpdateModel and AddModelError that you find in regular ASP MVC controllers, so if you are rendering your editor from a custom controller you can implement it easily like this:
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
You can find a nice succinct example in Orchard.Blogs.Controllers.BlogAdminController.
As an aside, you might recognise IUpdateModel and prefix from developing your content part driver - this abstraction is extremely versatile as it allows you to deal with multiple editors being updated at the same time (this is how stuff like content parts, fields etc have been implemented). It allows you to do some cool stuff like edit multiple content items on the same page. We use this at my work to implement a custom forms editor which has some nice features like drag and drop design etc.

Can Umbraco pass a model to view

I am quite new to this Umbraco MVC.
I need to pass some data bound to a model to my partial view from the GET action method.
This simply is not working in a regular MVC way.
[httpget]
public ActionResult Membership()
{
SupplierMembershipInfoModel mm = new SupplierMembershipInfoModel();
mm.ProductPackage = "sssssssss";
ViewBag.status = Request.QueryString["status"];
return PartialView("MembershipPartial", mm);
}
my view:
#model Umbraco.Web.Models.SupplierMembershipInfoModel
some html.....
<td>#Model.ProductPackage</td>
I don't get data here...and the debug never hits the action. But it hits any POST action method.
I know i am doing something wrong...but just don't know what the mistake is??
Any ideas??
As #Sebastiaan points out, the best place to start is the Umbraco community site. There is documentation specific to your issue here: http://our.umbraco.org/documentation/Reference/Templating/Mvc/child-actions
In a nutshell, you want to display a child action on your page and Umbraco uses SurfaceControllers for this. A SurfaceController is simply a Controller that inherits from Umbraco.Web.Mvc.SurfaceController. This provides you Controller with access to the Umbraco context - see here (http://our.umbraco.org/documentation/Reference/Templating/Mvc/surface-controllers).
Either way, you should read the whole documentation section on templating as it will give you a lot of insight into how Umbraco MVC is managed.

Creating n-tiered with MVC 4 & EF 5

I'm working on creating n-tiered application where I will have two separate project
1) project EF (where it will have all my edmx...)
2) project MVC 4 (internet application.)
In my EF i have, I have my .edmx file and it generate couple of classes with all props as show below (as sample)...
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class Requester
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
<//more...........>
}
everything is good so far!!
Back to MVC project
Now I will be creating a new Controller in my MVC project and when I'm trying to create Scaffolding and provide the Controller name and Controller expects a Model so the real question is:
What Model should I be passing here?
should I have the same class that EF created? or should I be creating another Model in my 'Model Folder` (MVC) and bind it? if yes than am I not creating duplicate property if I go ahead and create my same Model in MVC model Folder project?
What I'm trying to do? : Well my purpose of this exercise is to have my Data Access Layer (DAL) totally separate from MVC project.
any thoughts?
I'll suggest to create a view model so you can decorate the properties with view related stuff (i.e. UIHint). Also, this view model will be a reduced version of the class (for example, it can contain just the id of a related object instead of the whole object) making it easier for using as action parameters.
Also, you are talking about objects here, try not to think about "Data".
MVC really needs to be renamed VMVC - ViewModel View Controller.
The models in MVC have nothing to do with EF, Persistence, or your domain. They are a composition of multiple sources of data/settings/things which are represented/required in the View.
So create new View Models for your Views.
Edit:
All examples/tutorials which use EF Code First Models as View Models, are terrible tutorials / examples. They teach you bad practice because in the real world, you would never, and should never use those directly in your view.
The ViewModel is a composition or aggregation of data that's going into your view. For example:
If you had a product detail page, you might get the Product information from the Database, the availability of the product from a Web Service, your Shopping Cart from some Cache.
These would be composed into a ViewModel which represents the View that you're displaying. And rendered.
ViewModels should not be shared between views because if you change a ViewModel you change the meaning of the views that share that View Model.

How to expose and call methods on MVC 4 user controls

I am converting my asp.net site to MVC 4. My site has a control called loginbox that prompts the user for username and password. The control also exposes a method called IsLoggedIn that a hosting page can call. I want to continue to encapsulate the login logic in my loginbox control and call it in a similar fashion from a parent level page (i.e loginBoxInstance.IsLoggedIn()). How do I do that?
MVC doesn't have a concept of user controls. The whole setup of MVC is to separate logic from the view. You could achieve a similar setup by creating a separate controller and a partial view.
Then in your main view you could call RenderAction on the controller, which renders the partial view. However, this is only valid for the rendering stage, so something like IsLoggedIn() is not something you can (or should) do in MVC.
Example:
Controller
public class LoginController
{
public ActionResult Login()
{
return PartialView();
}
}
Partial View
// Place this file in Views/Login/Login.cshtml
<div>
<!-- Your markup -->
</div>
Main view
#Html.RenderAction("Login", "Login")
This will allow you to separate the view part (and also the logic) of the login rendering into a separate controller and view, which can be included in another view.
However, what you probably want is something like Action-attributes or inherit from a base controller class which handles all this for you.
The paradigm of MVC versus Web Forms is very different, and I think you should look into a more appropriate way of doing this.