Well im kinda new in Asp.net Mvc and im learning alone from scratch, i have a aplicattion that controls expends and earnings and what i am trying to do now is, basing on a list of earnings and expends give me the balance from a user, im having a lot of problems trying to control this and i dont know if i am doing it the right way
Here is my model:
public class Balance
{
public int BalanceId { get; set; }
public List<Expense> Despesas { get; set; }
public List<Earning> Rendimentos { get; set; }
public string ApplicationUserId { get; set; }
}
Soo what i did was, first trying to control when the user inserts a Earning or a row like, verifying if the User already exists on the database in the control method Create on the expenses and in the earning, if it doesnt exist he add the aplicationUserId and the expensive or the earning.
I want that the balance appears in every page, soo i added this to my Layout.cshtml
<li>#Html.Action("GetBalance", "Home")</li>
it calls the controller GetBalance:
public PartialViewResult GetBalance()
{
var userId = User.Identity.GetUserId();
var balance = db.Balance.Where(d => d.ApplicationUserId == userId);
return PartialView("_GetBalance",balance);
}
Send to the view _GetBalance the balance model:
#model <MSDiary.Models.Balance>
<p>Saldo: #GetBalance()</p>
#functions
{
HtmlString GetBalance()
{
decimal saldo = 0;
if (Model.Expense.Count != 0 || Model.Earning.Count != 0)
{
foreach (var item in Model.Despesas)
{
balance += item.EarningValue;
}
foreach (var item in Model.Rendimentos)
{
balance -= item.ExpenseValor;
}
}
return new HtmlString(balance.ToString());
}
}
What i want to know is, if there is a easyer way to do this, or what i can do to do what i want, i cant get it why my view expects something different can someone explain me what i am doing wrong?
Ps: Sorry for the long post and English, but i want to learn more :)
Firstly, the model #model <MSDiary.Models.Balance> needs to be changed to:
#model IEnumerable<MSDiary.Models.Balance>
Also, the method GetBalance should ideally be placed in a class not in GetBalance partial view. You could achieve this two ways, either through extension methods or have a Balance View Model that has the calculated balance as a property which is then passed down to your view.
As an example via an extension method:
public static class BalanceExtensions
{
public static string GetBalance(this Balance balance)
{
string displayBalance = "0:00";
// Your logic here
return displayBalance;
}
}
And then in your Partial View you can use the new HTML Helper:
#Html.GetBalance();
As an additional note I would change List to IEnumerable for expenses and earnings as it appears you are only exposing the data and not manipulating the data.
Your model would then look like:
public class Balance
{
public int BalanceId { get; set; }
public IEnumerable<Expense> Despesas { get; set; }
public IEnumerable<Earning> Rendimentos { get; set; }
public string ApplicationUserId { get; set; }
}
#Filipe Costa A few things here.
You should probably name your view the same thing as your method. The underscore preceding the name is fairly standard so I would suggest using that same name for the method. If the name of the method and view are the same you can simply pass in the model and not have to do the name + model signature of PartialView method. It's simpler.
Aside from that your code is fine but your .cshtml partial view should have this for the first line. That will accept the list you're passing.
#model IEnumerable<MSDiary.Models.Balance>
<h1>#Model.BalanceId</h1>
#*Do other stuff!*#
Related
I'm getting started with Razor pages and I have the following problem:
I have this model
public class Order
{
public int OrderId { get; set; }
public string Customer { get; set; }
public List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
public int OrderItemId { get; set; }
public string Item { get; set; }
public decimal Price { get; set; }
}
I'm binding it like this on the Edit.cshtml.cs
public class EditModel : PageModel
{
[BindProperty]
public Order Order { get; set; }
public void OnPost()
{
}
}
And in my Edit.cshtml I use it this way
#for (byte i = 0; i <= 5; i++)
{
<input asp-for="Order.OrderItems[i].OrderItemId" />
<input asp-for="Order.OrderItems[i].Item" />
<input asp-for="Order.OrderItems[i].Price">
}
My loop has to be always from 0 to 5, but the OrderItems collection can have even less than 6 items in it.
Now, this works fine in the New.cshtml page where the Order is a new object and the OrderItems is empty. But when I'm trying to edit an existing record I'm getting an error:
ArgumentOutOfRangeException: Index was out of range.
Must be non-negative and less than the size of the collection.
Is there a way to overcome this error without having to manually fill in the OrderItems collection to match the loop's length?
First of all, I believe you should not use a For loop with, let's say 5 iterations, without knowing for sure that you have to iterate 5 times. Maybe you could use a ForEach loop insteed or rething something in your view.
That's said, even if it is not a clean way, you can simply add a surrounding if statement around your inputs. Something like :
#for (byte i = 0; i <= 5; i++)
{
#if(Order.OrderItems[i] != null)
{
<input asp-for="Order.OrderItems[i].OrderItemId" />
<input asp-for="Order.OrderItems[i].Item" />
<input asp-for="Order.OrderItems[i].Price">
}
}
But again, using a ForEach loop would be a far better choice.
EDIT
Based on your comment, here is what you can do :
#if(Order.OrderItems[i] != null)
{
<input asp-for="Order.OrderItems[i].OrderItemId" />
<input asp-for="Order.OrderItems[i].Item" />
<input asp-for="Order.OrderItems[i].Price">
}
else
{
// new form to post the 3 inputs, allowing to reload the page with the new non null values ...
}
Based on comments it sounds like you're indicating that your model must have (at least) 6 elements in its list. If that's the case then that logic belongs on the model. Perhaps something like this:
public class Order
{
public int OrderId { get; set; }
public string Customer { get; set; }
private List<OrderItem> _orderItems;
public List<OrderItem> OrderItems
{
get { return _orderItems; }
set
{
_orderItems = value;
if (_orderItems == null)
_orderItems = new List<OrderItem>();
while (_orderItems.Count < 6)
_orderItems.Add(new OrderItem());
}
}
public Order()
{
// invoke the setter logic on object creation
this.OrderItems = null;
}
}
There are of course a variety of ways to organize the logic, this is just one example. But the point is that if the model must have at least 6 elements in its list then the model is where you would guarantee that. (Alternatively, if you feel that in your domain the view should be where this logic is guaranteed and the model can have other list lengths in other places that it's used, then I guess you could put the same logic on the view. But that seems unlikely. Logic generally belongs in models, views should just bind to those models.)
Is there a way to overcome this error without having to manually fill in the OrderItems collection to match the loop's length?
No. Well, depending on how you define "manually". Do you need to write code somewhere to perform your custom logic? Yes. Do you need to repeat the same code everywhere that you use it? No, that's why it belongs on the model.
Or, to put it another way: "Smart data structures and dumb code works a lot better than the other way around." -Eric Raymond
I am the beginner in MVC and I have a web application, where in my controller I declare a list of objects (feedback from visitors) and then send it to the view, which displays it. It looks like this. Declaration:
public class TrekFeedbackItem
{
public string trekid { get; set; }
public string comment { get; set; }
public string author { get; set; }
public TrekFeedbackItem(string trekid, string comment, string author)
{ this.trekid = trekid;
this.comment = comment;
this.author = author;
}
}
And usage:
List<TrekFeedbackItem> feedbackList = new List<TrekFeedbackItem>
{
//constructor called, data entered into the list
}
return View(trekname, feedbackList);
However, now I need to pass also another list, lets call it relatedblogsList. As a first step, I decided to encapsulate my feedbackList into the ViewModel (and once it works, add another list of different objects.)
public class TrekViewModel
{
public List<TrekFeedbackItem> feedback { get; set; }
}
and fill the data like this:
TrekViewModel trek = new TrekViewModel();
trek.feedback = new List<TrekFeedbackItem>
{
//insert data here
};
return View(view, trek);
The problem is - how to send this model to the partial view and how to access it?
Thank a lot
You can pass data into the partial view like below
from the controller return this view:
return PartialView("_partial_viewname", trek);
then in the beginning of the partial view:
#model Models.TrekViewModel
after that you can use Model.feedback inside the partial view.
Set return type of your action controller to "PartialView" rather than "View".
return PartialView("_yourPartialViewName", yourObject);
In case, if application does not work as expected, build it and re-run it.
I'm working on a website, where I need to retrieve pricelists, from another database on the same SQL Server as my Umbraco database.
It's a requirement that it has to be in a separate database.
I have made a new connection string Pricelist and used EF database-first.
PriceList repository:
namespace UmbracoCMS.Repository{
using System;
using System.Collections.Generic;
public partial class Prisliste
{
public string Kode { get; set; }
public string Speciale { get; set; }
public string Ydelsesgruppe { get; set; }
public string Gruppe { get; set; }
public string Ydelse { get; set; }
public string Ydelsestekst { get; set; }
public string Anaestesi { get; set; }
public string Indlæggelse { get; set; }
public Nullable<double> Listepris { get; set; }
public Nullable<int> WebSort { get; set; }
public string YdelsesTekstDK { get; set; }
public string Frapris { get; set; }
public Nullable<int> Sortering { get; set; }
}
}
PriceListController class:
using System;
using System.Linq;
using System.Web.Mvc;
using UmbracoCMS.Repository;
namespace UmbracoCMS.Controllers{
public class PriceListController : Umbraco.Web.Mvc.SurfaceController {
[HttpGet]
public PartialViewResult GetPriceList(string contentTitle){
var db = new PricelistContext();
var query = from b in db.Prislistes orderby b.Speciale select b;
Console.WriteLine("records in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Speciale);
}
return PartialView("~/views/partials/PriceList.cshtml");
}
}
}
What I want is to load the prices for a treatment, based on a property on the document type. I'm just not sure how do this in umbraco since I'm fairly new a umbraco.
So when a treatment page is requested, I need to take the property ContentTitle value. Use it to retrieve all records with the same Speciale and display them in a list/table.
With a query
.where(b.Speciale = contentTitle)
It would be great if someone could help a little, or lead me in the right direction.
Also is it possible to do it in the same http request? Or should I use partial view or macros to both get the properties of the document type, from the umbraco database, and the records from the pricelist database at the same time when a user go to the treatment page?
Or is there a better way to do this?
Update:
Thanks a lot, for the great answer Ryios.
I got a question more.
using System;
using System.Linq;
using System.Web.Mvc;
namespace UmbracoCMS.Controllers
{
public class PriceListSurfaceController : Umbraco.Web.Mvc.SurfaceController
{
public ActionResult GetPriceList(string contentTitle)
{
PricelistContext.RunInContext(db =>
{
var result = db.Prislistes.OrderBy(p => p.Speciale);
});
return View(result);
}
}
}
I got it working, so it call the method and the data from the Pricelist Database is shown in:
var result = db.Prislistes.OrderBy(p => p.Speciale);
Now I just need to get the list of prices out to the view again, so I can show a list or table of the prices.
Do you have a suggestion on how I can this in Umbraco. Normally I would return a ViewModel in MVC like:
return View(new ListViewModel(result));
and use it in the view like:
#model Project.ViewModels.ListViewModel
So I can loop through it.
But I want to still have the properties from the the "Home"/"TreatmentPage" Document type.
Should I do it with a partialView or is there a better way?
Solved
I thought I wanted to share it, if anyone else is in a similar situaction.
Controller:
namespace UmbracoCMS.Controllers
{
public class PriceListSurfaceController : Umbraco.Web.Mvc.SurfaceController
{
public PartialViewResult PriceList(string contentTitle)
{
List<Prisliste> result = null;
PricelistContext.RunInContext(db =>
{
result = db.Prislistes.Where(p => p.Speciale == contentTitle)
.OrderBy(p => p.Speciale).ToList();
});
var model = result.Select( pl => new PrislistVm()
{
Speciale = pl.Speciale,
Listepris= pl.Listepris
});
return PartialView(model);
}
}
}
ViewModel:
namespace UmbracoCMS.ViewModels
{
public class PrislistVm
{
public PrislistVm()
{
Results = new List<Prisliste>();
}
public List<Prisliste> Results { get; set; }
public string Speciale { get; set; }
public double listepris { get; set; }
}
}
View/PriceListSurface:
#model IEnumerable<UmbracoCMS.ViewModels.PrislistVm>
#{
ViewBag.Title = "PriceList";
}
<h2>PriceList</h2>
#foreach (var item in Model)
{
#item.Speciale
#item.Listepris
}
Your going to have a memory leak if you load your EF context like that. I recommend creating a method to wrap it for you with a llambda callback. Put it in your context class.
public static void RunInContext(Action<PricelistContext> contextCallBack)
{
PricelistContext dbContext = null;
try
{
dbContext = new PricelistContext();
contextCallBack(dbContext);
}
finally
{
dbContext.Dispose();
dbContext = null;
}
}
//Example Call
PricelistContext.RunInContext(db => {
var result = db.PrisListes.OrderBy(p => p.Speciale);
//loop through your items
});
To get the Value of the DocumentType, it depends on the calling context. Assuming you are using a Razor Template that is attached to the document type, that is associated with a Content Page.
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "ContentPageLayout.cshtml";
}
#* Call GetPriceList on PriceListController with Parameter contentTitle *#
#Html.Action("GetPriceList", "PriceListSurface", new { contentTitle = Model.Content.GetPropertyValue<string>("ContentTitle") });
In the above example, I have created a document type with a property called ContentTitle that is associated with a view called ContentPage. Then I created content in the backoffice Content section called "Home" that uses the document type. Giving me a url like
http://localhost/home
Also, your SurfaceController will not work. Umbraco's logic for mapping the routes for surface controllers has some requirements for your surface controller's naming conventions. You have to end the name of the class with "SurfaceController" and then it get's called PriceListSurfaceController, then it maps the controller with a name of "PriceListSurface".
Here's the documentation for the SurfaceController features.
http://our.umbraco.org/documentation/Reference/Mvc/surface-controllers
Using a surface controller is the right logic. It's not good practice to have your Data Layer code calls in the UmbracoTemplatePage. 1, because RazorTemplates are interpreted/compiled and SurfaceController's are JIT compiled int the dll, so SurfaceController code is WAY faster. 2 Because you can make asynchronous Controller calls in MVC Razor. If it was all in the view it would make it really difficult to convert everything to be asynchronous. It's best to keep server side logic in a controller.
Optionally, you can Hijack an Umbraco route and replace it with a custom controller that doesn't have to inherit from SurfaceController, which makes it possibly to surface content to the browser that is or isn't part of umbraco.
http://our.umbraco.org/documentation/Reference/Mvc/custom-controllers
You can also create a new section in the backoffice to manage your Price List "the ui framework for building one is written against AngularJS"
http://www.enkelmedia.se/blogg/2013/11/22/creating-custom-sections-in-umbraco-7-part-1.aspx
I have something like this
public class ResumeVm
{
public ResumeVm()
{
EducationVms = new List<EducationVm>();
}
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<EducationVm> EducationVms { get; set; }
}
public class WorkExperienceVm
{
public string Title { get; set; }
}
I now want to make an editor template for each of the EducationVms, I made a Template for 1 Education Vm and tried to use
#Html.EditorForModel("WorkExperienceVm")
but it does not know how to pass in the EducationVms
If I do
#Html.EditorForModel("WorkExperienceVm", #Model.EducationVms )
It gets made as it expects only 1 Vm to be sent in.
// View (WorkExperienceVm)
#model ViewModels.WorkExperienceVm
#Model.Title
The EditorForModel overload that you're using is incorrect. EditorForModel produces an editor template for the current model (i.e. the ResumeVm) and the string you're passing in is the additional view data object, not the name of the view.
I'm assuming that "WorkExperienceVm" is the name of the view. Try using EditorFor:
#for(int i = 0; i < Model.EducationVms.Count; i++)
{
Html.EditorFor(m => m.EducationVms[i], "WorkExperienceVm")
}
An alternative is to create a template that's actually called EducationVm.cshtml and type it to EducationVm, then you can just do the following and the framework will figure out that you want the template called for each item in the collection:
#Html.EditorFor(m => m.EducationVms)
Unfortunately this approach can't be achieved using UIHints or passing in the view name manually into the helper, though that's fairly unlikely to get in your way if you don't mind adhering to strict naming conventions for your templates.
I wrote another answer a while ago explaining the differences between the different helpers for editor templates. It deals specifically with the "label" helpers but the same principles apply to the "editor" helpers.
Let's say i have 2 files located in the same folder.
/Test/View.cshtml
<h1>File that needs to be loaded in to a string</h1>
/Test/Content.cs
public class Content {
public string GetView()
{
Return View("/Test/View.cshtml",someModel)
}
}
It should not cair about the RouteData from Web.Config
The point of doing this is, so that i am able to retrieve the GetView and use it elsewhere.
I know this question and approch is wierd but i am in a uniq situation developeing a CMS system, so i really need something like this.
How could i achieve this :)?
Update: Explanation
_Layout.cshtml
This file has no RenderBody as it normally has. Instead it has different Areas like this one.
#{
Render r = new Render("Content");
}
#r.Print()
Each area are printing out different modules, fx: a newsletter or a gallery. And for that to be possible this is done:
public interface IModule
{
string Name { get; set; }
int Id { get; set; }
string View();
}
public class ModuleList
{
public List<IModule> Modules = new List<IModule>();
public ModuleList()
{
Modules.Add(new ContentView() { Name = "Content" });
Modules.Add(new GalleryView() { Name = "Gallery" });
Modules.Add(new NewsletterView() { Name = "Newsletter" });
}
}
And here is is the ContentView Class (One of many Modules)
public class ContentView: IModule
{
public string Name { get; set; }
public int Id { get; set; }
DbModulesDataContext db = new DbModulesDataContext();
public string View()
{
var q = (from c in db.mContents
where c.Id == Id
select c).FirstOrDefault();
return ("<h1>"+q.Html+"</h1>");
}
}
As you can see right now the html is inline with the c# but i want it the other way around. (i want the View() to work together with a cshtml file)
Does it make a little more sence now?
I finaly found my solution!
It's right there!
http://razorengine.codeplex.com/
Thank you for trying though :)