MVC3 Razor Help required - c#

I'm hoping you guys can answer me a question?
I've only just started out using ASP.NET MVC3 have come unstuck at a certain point. I've been learning this stuff from books and I'm slightly unsure on a few things.
Can a VIEW, only have one #Model reference?
At the moment I have a VIEW setup with a HTTP-POST on a ViewResult, that validates the data in the View, entered by the user and then "on post", passes this info to a method that writes it back to a database(ADO.NET - Access). Now I need to change my VIEW, so that I can replace a couple of my text boxes for Dropdownlistfor controls. The Data to populate these controls will need to be passed in from the Database.
Would I be correct in saying that this data needs to be passed in the HTTP-GET Viewresult of the page, and if so, can i reference more than one #Model in this same View (*.cshtml).
I have a class that takes in the user response, and this is referenced in the View. But will i need to create a new class for the dropdownlist data and reference that too. So that in the background I populate the data into a SelectListItem, pass it to the View and then populate each drop down control within the view?
I'm sorry if this is poorly written, very hard to explain, I find learning from books hard and I'm pretty stuck now. Any help would be appreciated. Just to give me an understanding of how this all wraps around. I'm comfortable with the C# syntax, but very unsure of MVC3!

There are two ways you can handle this.
Use a View Model.
In this scenario you have a class that contains your data model as well as other things required by the view, so something like this:
public class ViewModel
{
public MyDomainModel Model { get; set; }
public IEnumerable<SelectListItem> SelectListItems { get; set; }
}
Use ViewBag.
In this case you add everything extra into the ViewBag dictionary. So in the controller, you'd have stuff like this:
ViewBag.SelectListItems = new SelectListItem[] { ... };
Then you can reference in the view itself
#Html.DropDownList("myselectlist", ViewBag.SelectListItems)

I think that this will help you pluralsight mvc3 intro. It sure helped me

Related

Modify IPublishedContent properties in Umbraco custom controller

First of all, I realise that the core of my problmen probably is the way that I'm trying to solve it, so let me first explain what I'm trying to do.
I have a Layout where I output a property.
Layout.cshtml
inherits Umbraco.Web.Mvc.UmbracoTemplatePage
...
//More of the layout here
<title>#Model.Content.GetPropertyValue("title")</title>
...
This is the base of the other templates:
FullWidth.cshtml
#{ Layout = "Layout.cshtml"; }
... layout here
This all works well, I make sure every document type has a property called title and it gets printed all the time.
Now I'm creating a page, where some data from a database is being displayed. So I created a custom controller:
public class ProductController : RenderMvcController
{
public ActionResult Index(Rendermodel model, int id)
{
var viewModel = new CustomRenderModel(model.Content);
viewModel.Product = Database.GetProductById(id);
return CurrentTemplate(viewModel);
}
}
This works great too, but the next thing I want to do is also set the title based on whatever is retrieved from the database. Something like this:
var viewModel = new CustomRenderModel(model.Content);
var product = Database.GetProductById(id);
viewModel.Product = product;
viewModel.Content.SetPropertyValue("title", product.name");
Obviously this doesnt work because the IPublishedContent is readonly. I'm just wondering what the best way is to modify a property like that.
I realise that exposing a SetPropertyValue is a bad idea probably, but what would be the way to solve this.
I would render this title in a separate partial view and give that partial view a specific model to render.
Have a look at this blog post I wrote which shows you how to do that.
http://www.codeshare.co.uk/blog/how-to-optimise-your-website-for-search-engines-seo-in-umbraco/
Kind regards
Paul
I know, this is an old post, but other people might search for a solution to this question. It absolutely makes sense to be able to overwrite property values, especially in route hijacking scenarios. The solution is to write an own implementation of IPublishedContent. It only needs a few lines of code. The solution is shown in this blog post:
https://www.formfakten.de/themen/2018/08/publishedcontent-with-overridden-properties

Get controller properties in HTML, is everything meant to go in a viewbag?

From what I read in various tutorials, or simply the sample project, the Controller use the ViewBag to store anything that will be dipsplayed on the page.
In the Controller I can just type ViewBag.AnythingIWant = "Foo";, and it'll render in the HTML. Apparently that's what is done in the sample project, at least for title and various texts.
But most of the text is hardcoded in the HTML and obviously I don't want that. Considering I'm not new to C# or MVC in Xamarin (mobile development), I feel like I should grasp this pretty quick, but I don't. Could someone clarify to me the following :
My Controller knows the ViewModel (which does most of the work) and himself uses the Model privately. I'm used (from iOS dev) for the controller to be the last layer of UI, and inside the controller I would just have all my labels and whatever I want, and I can fill them with whatever is available in the ViewModel.
Here, there is this HTML layer that I don't know how to connect to the controller.
I have a strong feeling that putting everything in the ViewBag cannot be the way to go. Could anyone briefly reveal the piece I am missing to use proper objects inside the HTML ?
Razor might be what's confusing me, considering whatever I add publicly in my Controller, I can't find it in the related HTML using #MyProperty
I know this is pretty broad question but I know that I only miss a small piece of knowledge to unlock everything.
As noted in the comments, pass a ViewModel to the View to be rendered!
Controller
public ActionResult Index() {
var viewModel = new MyViewModel { Name = "some string" };
return View("Index", viewModel);
}
Index.cshtml
#model MyViewModel #* Tell Razor which ViewModel to expect *#
#{ string name = Model.Name; }

MVC Master-Detail CRUD [duplicate]

This question already has answers here:
POST a form array without successful
(5 answers)
Closed 7 years ago.
I'm starting with MVC and i have some basic questions that maybe you can orient me a little bit:
I'm Using MVC5 with Razor and EntityFramework 6. No AngularJS skills here.
I have a classic Master-Detail CRUD where i need to create Order and OrderItems. My idea es that when you create the order, you can add the items in the same form and then with one SAVE button create both records on the database (The Order and the Items).
I've created the "Orders" CRUD very good with scaffolding, and it works perfect. But now i need to add to the same VIEW the items, and here is what i'm getting lost and try different ways to do this:
BINDING ISSUE: I thought that probably i could add the list of OrderItems to the binding header on the CREATE event. My OrderController has this method:
public ActionResult Create([Bind(Include = "Id,Date,*other fields*")] Order order) and it works fine with the ORDER CRUD operations. But, now, if need to add a List to the list of fields binded on that header, is that possible? How should i save the data in the View then?
JSON: Another way i thought, was to remove the Binding header and use Json, but all the examples i've seen was using AngularJS and i have all the site done except for this CRUD, i preffer to let that option for the real last chance. On the other hand, i've found this: https://www.youtube.com/watch?v=ir9cMbNQP4w and it's exactly what i need to do, but: It's on MVC4 and not MVC5, and also i have all my entities validation in my model (extended) class and some of them in the controller as well (exclusively the ones related to the Creation or editing the order). Tell me if i'm wrong here please!
PARTIAL VIEW: The last way i've just tried was with Partial View. I've created succesfully the Initial data load based on this tutorial: http://dotnetmentors.com/mvc/render-partialview-with-model.aspx , but after that, i need to add new items to my order, or edit/delete the existing ones and here is where i get lost: Should i have different CREATE/EDIT methods for the partial views? How i send the data then? How i can use only one SAVE button that saves everything at the same time?
I'm getting more lost when i look for more information.... so, here i am asking for help to you guys !
Thanks a lot in advance !!
Create a custom view model:
public class NewOrderViewModel
{
public Order order { get; set; }
public OrderItem[] orderItems { get; set; }
}
Then you can use this in the view by changing #model NewOrderViewModel at the top and you will be able to use like:
#Html.TextBoxFor(m => m.order.Phone);
#Html.TextBoxFor(m => m.orderItems[0].ItemName);
You will need some javascript to copy the html and create new form elements for each new orderItem the user wants to add.
Then your controller signature would look like:
public ActionResult Create(NewOrderViewModel content)

passing multiple models to controller to build ViewModel

So I'm consuming a RESTFul API to get the data I need. This API returns json and i converted this to C# models. The API returns some general info about a vendor and an array with products. The array of products also consists out of arrays for pricing information and product availability etc...
The problem im facing is that when a product is selected by a user to buy i have to gather specific information out of the different array's. Currently I've made a ViewModel for the data that needs to be send to process the order. This is done by binding the actual data using hidden fields and use a HttpPost from the view, resulting in +/- 30 hidden fields to set the proper data values.
I'm kinda new to MVC and this seems dirty. I thought i would be able to pass the models(for example the VendorModel,ProductModel,PricingModel,AvailabilityModel) from the view(with a POST) to the controller and create the ViewModel(based on the models send) so that i can send that to the API.
Is this actually how it should be done or is my design faulty and should i approach this differently?
A side note: One of the things i found is that most people suggest to use an identifier to get the data you need but the problem is that the API doesn't have the right calls to get Product, Pricing, Availability data based on Id, its just one big object with array's based on the search query.
Edit
So after some information i decided to try out nested models and created a viewmodel like this:
public class TestViewModel
{
public TestViewModel()
{
productInfo = new ProductInfo();
}
public ProductInfo productInfo { get; set; }
}
My view is like this(super simpel):
#using (Html.BeginForm("CreateOrder","Products"))
{
//Vender info etc...
//This is how i render partial view now:
{Html.RenderPartial("Info/ProductInfo", Product.ProductInformation.ProductInfo);}
<input type="submit" value="Order" class="btn btn-default" />
}
My controller(TestViewModel.ProductInfo is always null):
public ActionResult MakeReservation(TestViewModel testViewModel)
{
//Doesnt do anything just debugging TestViewModel
return View();
}
I'm not posting any inputs but just want to pass the modal with the data to the controller. How will MVC know which data to bind, because now it doesnt bind. Do i have to bind it myself somehow?
I had the similar situation and I have one suggestion, you can pass all the models to the view as save in a javascript object as JSON using the example code which I used like below-
<script type="text/javascript">
var pageBlockOptionsJSON = #(Html.Raw(Json.Encode(DesignOrderBlocks)));
var controlTypeJSON = #(Html.Raw(Json.Encode(controlList)));
</script>
Then you can do all the manipulations using jQuery to structure and create a javascript object and post that object to Controller Action. You can create the same or exact structure which is needed on the server. As specified in this url - http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/
In this way you don't need to have use huge amount of hidden fields and you can do all the dirty work on the client side using jQuery.
I am sure this will help you out in doing the thing in the right way. Let me know if you need some details.
For people that somehow find this questions i solved this issue by saving the model to an database as an search result using entity framework. After getting the result i save it and create a viewmodel. After posting i send the id's that entity framework generated and search the right models in the database creating a new postviewmodel.

MVC3.0+c#+razor: How to create ONE page where posts are shown and comment create part

I'm trying to create a weblog with mvc. I made a database code first with EF. Now I have a page where you can see one post per page. Below I want to show all comments on the post. Thats all working fine. But now I want to make a create comment functionality on that same page.
I'm not sure how to do this? Because this has to create a new object 'comment' instead of the 'post' object I've set as Model in my view. So I've got different models in my view? I don't think that's possible right? Maybe I can just use the 'post' model because it has comments as a list<> in it?
Do I need to use partial views for this or maybe a model view?
Hope you know what I mean and what I'm trying to accomplish. Tnx in advance for any help!
If your Post model contains a List<Comment> then you could of course use that. Even if you do go that route, using a ViewModel to wrap all of your model objects is never a bad idea.
Simply for the sake of maintainability, I would use partial views for the different models rendered on your page, but that's is purely a matter of personal preference.
Yes you can do it by using a partial view. Make a partial view that posts comments to server. Display this partial view below comments list. When user post the comment then submit it via json call and on success make html string of comment and append it in the comments list.
In this way your comment will be posted as well as loaded in comments list without reloading the whole model
Your post should have a comment collection of some sort. You should be able to just add a non-model-bound form; in your controller, you have your collection, just pull the data out of that.
What I mean is: in your view, you'll have something like
#Html.TextArea("CommentText")
In your controller:
public ActionResult Create(FormCollection collection) {
string commentText = collection["CommentText"];
Post p = ... ; // Not familiar with EF
p.Comments.Add(new Comment(commentText));
p.Save(); // ActiveRecord style, not sure about EF
}
It should be pretty straight-forward. I use ActiveRecord on NHibernate, so I'm not sure about Entity Framework specifically. Was there some specific problem you got stuck on?

Categories

Resources