I am new to MVC and Entity Framework, and would like some assistance in passing data to a model so that I can make my view a strongly typed view and get the information out as I need.
In the about action in the home controller i want to pull out data from my SiteContent table that is for the About Page
var sc = db.siteContents.Where( x => x.Page == "About").ToList();
return View(sc);
A couple of questions I have around this, is first, how do I get this into my Model SiteContent
public class SiteContent
{
public int ContentId { get; set; }
public string ContentType { get; set; }
public string Page { get; set; }
public string ContentHeader { get; set; }
public string Content { get; set; }
public DateTime OriginalPostDate { get; set; }
public DateTime UpdatePostDate { get; set; }
public string ImageFileName { get; set; }
public bool ContentReleased { get; set; }
}
I am uncertain on how I should proceed from here.
The from here I would like to use a strongly typed view to get the data by using my model.
Any and all help very much appreciated.
Thanks
Simon
Define your view like this:
#model IEnumerable<SiteContent>
<table>
<tr>
<td>ContentType</td>
// other data
</tr>
#foreach(var item in Model)
{
<tr>
<td>#item.ContentType</td>
// other data
<tr>
}
</table>
Related
I want to display a name in the razor page by select it from a model and pass it through Viewbag in the controller.
Controller
public IActionResult sheet()
{
var tp1 = _db.Topic.Where(t => t.sheet_id == 1).ToList();
var tp1name = tp1.Select(t => t.topic1name);
ViewBag.tp1name = tp1name;
return View();
}
Model
public class Topic
{
[Key]
public int topic_id { get; set; }
[Required]
public int sheet_id { get; set; }
[Required]
public string topic1name { get; set; }
[Required]
public string topic2name { get; set; }
}
public class Transaction
{
[Key]
public int id { get; set; }
[Required]
public int sheet_id { get; set; }
[Required]
public string topic1score { get; set; }
}
View page
#model transaction
<table class="table">
<tr>
<td rowspan="2">1</td>
<td rowspan="2">#ViewBag.tp1name</td>
<td rowspan="2">30</td>
<td>Below average</td>
<td>Average</td>
<td>Above average</td>
</tr>
It returns
System.Linq.Enumerable+SelectListIterator`2[UserLoginApp.Models.Topic,System.String] in the view page instead of topic1name
tp1 is a list of topics.
so when you do a select it creates a new Enumerable en for each item in tp1 it selects the value of topic1name.
Thus creating an Enumerable+SelectListIterator
I think you want the value of one item:
var tp1 = _db.Topic.FirstOrDefault(t => t.sheet_id == 1)
if(tp1 != null)
ViewBag.tp1name = tp1.topic1name;
I would like some direction on how to be able to list all the items under a certain category in a view. I have already searched around and can't find anything, If someone know of any other posts or articles please point me there. Other wise here is my model...
public class Category
{
[Key]
public int ID { get; set; }
[Display(Name = "Category")]
public string Name { get; set; }
public virtual ICollection<MenuItem> MenuItem { get; set; }
}
public class MenuItem
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public string Image { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
Thanks for any help anyone can provide.
assuming your category is set at the model
#foreach(var item in Model.MenuItem)
{
#Html.HiddenFor(x => item.ID)
<div>#Html.DisplayFor(x => item.Name)</div>
// carry on with other properties / markup
}
Say you want to loop over the MenuItem property in the Category model, in your view you'd have something like this:
At the top of the View, you'd have this:
#model Category
#foreach (var item in Model.MenuItem)
{
<tr id="menu-item">
<td>#id</td>
<td>#Name</td>
<td>#Description</td>
<td>#Image</td>
</tr>
}
#foreach (var item in Model.MenuItem)
{
<tr>
<td>#Name</td>
<td>#Description</td>
</tr>
{
At the moment I have this as my code:
public ActionResult Search(SearchModel model)
{
string url = "http://10.0.2.31/testwebapi/api/data";
WebClient wc = new WebClient();
wc.QueryString.Add("forename", model.Forename);
wc.QueryString.Add("surname", model.Surname);
wc.QueryString.Add("caseid", model.CaseId);
wc.QueryString.Add("postcode", model.Postcode);
wc.QueryString.Add("telephone", model.Telephone);
wc.QueryString.Add("email", model.Email);
wc.QueryString.Add("title", model.Title);
var data = wc.UploadValues(url, "POST", wc.QueryString);
var responseString = Encoding.Default.GetString(data);
return PartialView("~/Views/Shared/SearchResults.cshtml", responseString);
}
public class RootObject
{
public int Caseid { get; set; }
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Postcode { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public string DOB { get; set; }
public string Mobile { get; set; }
public string MaritalStatus { get; set; }
public string LoanPurpose { get; set; }
public bool CourtesyCall { get; set; }
public string isOpen { get; set; }
}
im not sure where i am going wrong i want it to be able to pull that data from the web api (which returns a json file). then what i want to do is send that data through to my partialview where a #foreach statement will put it into a table but i cant seem to get it to send the data it is interperating it as a string and i dont know why
this is how it is returning:
#model string
#{
Layout = null;
}
#foreach(var Case in Model)
{
<p>#Case</p>
}
Partial view code.
This is what my partial now looks like:
#model IEnumerable<Savvy_CRM_MVC.Models.RootObject>
#{
Layout = null;
}
#foreach (var m in Model)
{
<p>#m</p>
}
which when i run through the for each is gives me this Savvy_CRM_MVC.Models.RootObject
The problem is that you are binding you model to the raw JSON string.
you need to deserialize the JSON string to your RootObject class and use RootObject as the model for your view.
the following code user Newtonsoft JSON.net to deserialize the string;
var rootObjects = JsonConvert.DeserializeObject<RootObject[]>(responseString);
return PartialView("~/Views/Shared/SearchResults.cshtml", rootObjects);
and you view changes
#model IEnumerable<RootObject>
You are also going to need to change you view to display the properties of your model.
I have problem with how to and where to add if condition in view which has two models in a single view.
This is view
#foreach (service_provider SP in ViewBag.service_provider) {
<tr>
<td>#SP.Sp_email</td>
<td>#SP.Sp_name</td>
<td>#SP.city.Cityname</td>
</tr>}#foreach (picture img in ViewBag.pictures){
<tr>
<td><img src="data:image/png;base64,#Convert.ToBase64String(img.pic,0,img.pic.Length)" width="100" />
</td>
</tr>
}
This is picture model
public int PIC_ID { get; set; }
public string pic_name { get; set; }
public Nullable<int> belong_id { get; set; }
public byte[] pic { get; set; }
This is service_provider model
public int SPID { get; set; }
public string Sp_email { get; set; }
public string Sp_password { get; set; }
public string Sp_name { get; set; }
This is my controller
public ActionResult Index(){
ViewBag.service_provider = dc.service_provider;
ViewBag.pictures = dc.pictures;
return View();
}
The purpose of the above view is to display details of the service_provider with it's picture by where belong_id in picture equals SPID in service_provider. but I couldn't understand where do I add if condition.I'm using Database first approach
It would be much easier if you used a strongly typed model instead of the ViewBag. You can then add logic to your model or your controller. I personally it easier read and test. It also prevents syntax errors.
Models.cs
public class Picture {
public int PIC_ID { get; set; }
public string pic_name { get; set; }
public Nullable<int> belong_id { get; set; }
public byte[] pic { get; set; }
// added - your FK pointing back to the corresponding service_provider
public int SPID { get; set; }
// added - the corresponding service_provider
public service_provider ServiceProvider { get; set; }
}
public class service_provider {
public int SPID { get; set; }
public string Sp_email { get; set; }
public string Sp_password { get; set; }
public string Sp_name { get; set; }
// added
public ICollection<Picture> Pictures {get;set;}
}
Controller.cs
public ActionResult Index(){
var service_provider = dc.service_provider.Inculde(x => x.Pictures);
// var pictures = dc.pictures;
// code to add the pictures to the correct service_provider instance
// ideally this should already be reflected in your model.
// If you are using EF you should be modeling this using proper data relations
// that would allow you to execute an .Include statement on the retrieval
// and pass the model directly into the View without the need for an additional call to pictures as the service_provider would then already contain the relations
return View(service_provider);
}
View.cshtml
#model IEnumerable<service_provider>
#*This following line indicates that it is a list of service_provider hense the IEnumerable*#
#foreach (service_provider SP in Model){
<tr>
<td>#SP.Sp_email</td>
<td>#SP.Sp_name</td>
<td>#SP.city.Cityname</td>
</tr>
#*Iterate over the pictures on each model.
You can still split this if you want all service providers and then all pictures.*#
#foreach (picture img in SP.Pictures){ #*changed to still look at the model*#
<tr><td><img src="data:image/png;base64,#Convert.ToBase64String(img.pic,0,img.pic.Length)" width="100" /></td></tr>
}
}
Try:
#foreach (picture img in ViewBag.pictures)
{
if(img.PIC_ID == ViewBag.service_provider.SPID)
{
<tr><td><img src="data:image/png;base64,#Convert.ToBase64String(img.pic,0,img.pic.Length)" width="100" /></td></tr>
}
}
BTW - Maybe better way - is check in server side and return ONLY pics that you need??
I am developing a page which display data from service on the View and allow users to filter it.
There is a column for Countries, which allow users to filter.
I am not able to figure out a way to create a list of checkbox so that I can grab all selected values in one param like string[] countries (in the action method).
Can't use classic way :
<input type="checkbox" name="countries" value="USA" />USA<br />
<input type="checkbox" name="countries" value="Canada" />Canada<br />
This does pass the values in URL but doesn't set them back on post back (keeping checked onpostback).
I tried using checkboxlist (http://goo.gl/TUvZzu) but seemed to complicated for my Modal.
Since mine is a very straight forward Model :
public string Title { get; set; }
public string Website { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string State { get; set; }
public string Country { get; set; }
I appreciate your time and help.
You need to include a collection of countries within your view model to hold the selected values and allow them to be sent in the post.
I would also create a Country object to hold the Id, Name and Selected values.
In order for the model to be posted back you need to index each item in the view, this allows the model binder to pick it up.
Models
public class AModel
{
public AModel()
{
Countries = new List<Country>();
}
public string Title { get; set; }
public string Website { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string State { get; set; }
public string Country { get; set; }
// Country collection
public List<Country> Countries { get; set; }
}
public class Country
{
public int ID { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
View for loop
#for(var i = 0; i < Model.Countries.Count; i++)
{
<dt>
#Html.HiddenFor(m => Model.Countries[i].ID)
#Html.HiddenFor(m => Model.Countries[i].Name)
#Html.CheckBoxFor(m => Model.Countries[i].Checked)
</dt>
<dd>
#Model[i].Name
</dd>
}
Note the for loop instead of foreach to enable model binding and the hidden fields to allow the values to be posted back to the controller
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
Controller post
[HttpPost]
public ActionResult Index(AModel model)
{
//All the selected countries are available in the model
return View(model);
}
Working example