I am trying to display a list of Providers in a table.The code to get the list of providers is as follows
public ActionResult Index()
{
DAL2 dal = new DAL2();
Provider patientlist = new Provider();
List<Provider> providers = dal.GetListofProviders.ToList();
return View(providers);
}
The above code is working fine.I am getting the list of providers as expected.
The HTML code in the view is as follows
#model IEnumerable<ProviderDemo.Models.Provider>
#{
ViewBag.Title = "ProviderList";
}
<head>
<title>LIST OF PROVIDERS</title>
</head>
<body>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Provider Type</th>
<th>First Name</th>
<th>Last Name</th>
<th>Certification</th>
<th>Specialization</th>
<th>SSN</th>
<th>Facility Name</th>
<th>Contact No</th>
<th>Contact Email</th>
<th></th>
</tr>
<tbody data-bind="foreach: viewmodel">
<tr>
<td class="col-lg-2" data-bind="text: ProviderType"></td>
<td class="col-lg-1" data-bind="text: FirstName"></td>
<td class="col-lg-1" data-bind="text: LastName"></td>
<td class="col-lg-1" data-bind="text: Certification"></>
<td class="col-lg-1" data-bind="text: Specialization"></td>
<td class="col-lg-1" data-bind="text: SSN"></td>
<td class="col-lg-4" data-bind="text: FacilityName"></td>
<td class="col-lg-4" data-bind="text: ContactNumber"></td>
<td class="col-lg-1" data-bind="text: ContactEmail"></td>
<td><a class="btn btn-default" id="del" onclick = "return confirm('Are you sure, you want to delete');" data-bind="attr: { href: '/ProviderRegister/Delete/' + ProviderID }"> Delete </a>
</td>
</tr>
</tbody>
</table>
</body>
My Provider class is as follows:
public class Provider
{
public int ProviderID { get; set; }
public string ProviderType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Certification { get; set; }
public string Specialization { get; set; }
public string SSN { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
public string FacilityName { get; set; }
}
Provider Viewmodel
var Provider =
{
ProviderID:ko.observable(""),
ProviderType: ko.observable(""),
FirstName: ko.observable(""),
LastName: ko.observable(""),
Certification: ko.observable(""),
Specialization: ko.observable(""),
SSN: ko.observable(""),
ContactNumber: ko.observable(""),
ContactEmail: ko.observable(""),
FacilityName: ko.observable(""),
}
ko.applyBindings(Provider);
The list is not getting displayed in the table.There seems to be an error at the top of the html for the model.I dont understand why though.Am I doing something wrong here?Please guide me in the right direction.
Thanks a lot for all your help guys,but I made a mistake earlier.In the Index action ,I see the list of providers but I dont get any data in the view.So,I have the data in the controller but not in the view.
If you have a populated Model, you need to get the data from that out into you knockout model. So either use System.Web.Helpers.Json.Encode() or make your own JSON in the view.
Then load that data into your knockout view model.
var data = #Json.Encode(Model);
var ViewModel = function(data) {
var self = this;
self.Providers = ko.observableArray(data);
};
var viewmodel = new ViewModel(data);
ko.applyBindings(viewmodel);
and then in your foreach, use Providers instead of viewmodel
Related
I have passed the model to partial view,And then i need to bind some text fields to the model in the view.
#model SRINews.Domain.NewsTotal
#using (Html.BeginForm("UpdateNewsItem", "Home", FormMethod.Post))
{
<table class="table table-borderless table-cart" id="mytable" data-addclass-on-smdown="table-sm">
<tbody>
#foreach (var item in Model.items)
{
<tr class="newsRow" id="#item.ItemId">
<td class="cart-img nostretch">
<img src="#item.ImageUrl" alt="">
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="Personalized Name">
//#Html.TextboxFor(x=>x)
// I want to bind PersonalizedName to model
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="Country">
// I want to bind Country to model
</td>
</tr>
}
</tbody>
</table>
<input type="submit" class="btn btn-primary" value="Personal Details" />
}
Model
public class Items
{
public int ItemId { get; set; }
public string ItemCode { get; set; }
public string PersonalizedName {get;set;}
public string Country {get;set;}
}
public class NewsTotal
{
public int BaseItem { get; set; }
public string BaseName {get;set;}
public List<Items> items { get; } = new List<Items>();
}
Public ActionResult UpdateNewsItem(NewsTotal nTotal)
{
return View();
}
You want to use a traditional for loop so you can use the index to bind to your List<T> in the model, you'll also need to make items mutable, so you'll need to have a set for it as well or else you won't be able to submit anything:
//You'll need to make this mutable, so it can post the edited values
public List<Items> items { get; set; } = new List<Items>();
Then in your View:
#for(int i = 0; i < Model.items.Count; i++)
{
#Html.HiddenFor(x => Model.items[i].ItemId)
#Html.HiddenFor(x => Model.items[i].ItemCode)
<tr class="shoppingCartRow" id="#Model.items[i].ItemId">
<td class="cart-img nostretch">
<img src="#Model.items[i].ImageUrl" alt="">
</td>
</tr>
<tr>
<td>
#Html.TextboxFor(x=> Model.items[i].PersonalizedName, new { #placeholder = "Personalized Name"})
</td>
</tr>
<tr>
<td>
#Html.TextboxFor(x=> Model.items[i].Country, new { #placeholder = "Country"})
</td>
</tr>
}
I am using weather API in which user search weather for specific City or Country from view which is receive by controller as parameter,information about weather is completely working but I am just unable to return all that information back to view from controller.
view for search
<form action="searchbyname" method="post">
<input type="text" name="weather" placeholder="Find your location...">
<input type="submit" value="Find">
</form>
Controller
public ActionResult searchbyname(string weather)
{
string appId = "f40a39abac667183c127adefffcf88ed";
string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&APPID={1}", weather, appId);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
if (json.IndexOf("Error") == -1)
{
WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize<WeatherInfo>(json);
ViewBag.citycountry = weatherInfo.name + "," + weatherInfo.sys.country;
ViewBag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.sys.country.ToLower());
ViewBag.des = weatherInfo.weather[0].description;
//weatherimage
ViewBag.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.weather[0].icon);
ViewBag.temp = string.Format("{0}°С", Math.Round(weatherInfo.main.temp, 1));
}
}
return View();
}
View in which data should be shown
<table id="tblWeather" border="0" cellpadding="0" cellspacing="0" style="display:none">
<tr>
<th colspan="2">
Weather Information
</th>
</tr>
<tr>
<td rowspan="3">
<img id="imgWeatherIcon" />
</td>
</tr>
<tr>
<td>
<span id="citycountry">#ViewBag.citycountry</span>
<img id="imageurl" src="#ViewBag.ImageUrl" />
<span id="des">#ViewBag.des</span>
</td>
</tr>
Model class
public class ClimateModel
{
public class WeatherInfo
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public int dt { get; set; }
public string name { get; set; }
}
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Sys
{
public string country { get; set; }
}
public class Weather
{
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
public int humidity { get; set; }
}
}
}
I think you are mixing some concepts between WebForms and MVC. There is no runat="server", asp:Label or asp:Image on MVC. You must use with pure HTML elements.
Your code should looke like:
<table id="tblWeather" border="0" cellpadding="0" cellspacing="0" style="display:none">
<tr>
<th colspan="2">
Weather Information
</th>
</tr>
<tr>
<td rowspan="3">
<img id="imgWeatherIcon" />
</td>
</tr>
<tr>
<td>
<span id="citycountry">#ViewBag.citycountry</span>
<img id="imageurl" src="#ViewBag.ImageUrl" />
<span id="des">#ViewBag.des</span>
</td>
</tr>
</table>
EDIT 1: As #erik-philips pointed out, you should really create a model class.
EDIT 2: Take a look at HTML Helpers. The can make your life easier when binding models to views.
As Erik pointed out in his comment you could use a model to capture the api response, and then put it either in a viewbag, or a viewdata to be able to access it inside the view .
ViewBag.WeatherInfo = weatherInfo;
Then inside your view you can do :
var weatherInfo = ViewBag.WeatherInfo as WeatherInfo
This way you have access to your object inside the view
As requested here is how it can be used in your situation
#{
var weatherInfo = ViewBag.WeatherInfo as WeatherInfo
}
<table id="tblWeather" border="0" cellpadding="0" cellspacing="0" style="display:none">
<tr>
<th colspan="2">
Weather Information
</th>
</tr>
<tr>
<td rowspan="3">
<img id="imgWeatherIcon" />
</td>
</tr>
<tr>
<td>
<span id="citycountry">#weatherInfo.name , #weatherInfo.sys.country</span>
<img id="imageurl" src="your image link" />
<span id="des">#weatherInfo.weather.First().description</span>
</td>
</tr>
I can't figure out how to connect my model with my angular view in ASP.net MVC. I am trying to show the FirstName and LastName values from the User model.
Here is my view:
<table class="table" ng-app="UserApp" style="background: white;" height="1200">
<tbody ng-controller="SearchController">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="user in User">
<td></td>
<td>{{ user.FirstName }}</td>
<td>{{ user.LastName }}</td>
</tr>
}
</tbody>
Here is the controller:
public class SearchController : Controller
{
private GigDB db = new GigDB();
// GET: Search
public ActionResult Search()
{
List<User> users;
users = db.Users.ToList();
return View(users);
}
}
Here is the model:
public class User
{
[Key]
public int UserID { get; set; }
//[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
//[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
Lastly, the script:
var app = angular.module('UserApp', []);
app.controller('SearchController', function ($scope) {
$scope.model = #Html.Raw(Json.Encode(Model));
console.log($scope.model);
console.log($scope.model[0].FirstName);
});
What I am confused about, is the console.log in the script is working and shows the user objects correctly with all of the values. Also when I console.log #scope.model[0], that pulls the value correctly as well but in the angular view I cannot get the values to show at all.
Code C# like this to return Json object
public JsonResult Search()
{
List<User> users;
users = db.Users.ToList();
return JSon(users,JsonRequestBehavior.AllowGet);
}
and script should like this to call data:
app.controller('SearchController', function ($scope) {
$http({
method: 'GET',
url: '/SearchController/Search'
}).then(function successCallback(response) {
$scope.User= response.data;
});
});
It may help you
So, originally in my view I had:
<table class="table" ng-app="UserApp" style="background: white;" height="1200">
<tbody ng-controller="SearchController">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="user in model"> //model here instead of User..
<td></td>
<td>{{ user.FirstName }}</td>
<td>{{ user.LastName }}</td>
</tr>
}
and I thought that it was not working, but as it turns out the table just stretched far down on the screen and I couldn't see the values being shown. Oops.
I'm using VS 2015 and I created an ASP.NET MVC project and added a couple things (log in and register did work fine with Localdb called MyDatabase.mdf) that did work.
CRUD only create function in db the rest will come later.
But now I can't get this work. Inside the LocalDb called MyDatabase.mdf, I have created another table called Amsterdam:
[MyDatabase.mdf][1]
And this is my MainDbContext.cs - here I added
public DbSet<Amsterdam> Amsterdam { get; set; }
And in my Home folder I wrote Amsterdam.cshtml like this:
#model IEnumerable<MyFirstWebsite.Models.Amsterdam>
#{
ViewBag.Title = "Amsterdam";
var username = User.Identity.Name;
}
<h2>#username's Bestellijst Amsterdam</h2>
#using (Html.BeginForm())
{
<span>Enter new item: </span>
<br/>
<input type="text" name="new_item"/>
<br/>
<span>Public post?</span>
<input type="checkbox" name="check_public"/><br/>
<br/>
<input type="submit" value="Add Item"/>
}
<br/>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th style="text-align: center;">Id Bestelling</th>
<th style="text-align: center;">Details Bestelling</th>
<th style="text-align: center;">Time - Ontvangen Bestelling</th>
<th style="text-align: center;">Time - Verzonden Bestelling</th>
<th style="text-align: center;">Edit</th>
<th style="text-align: center;">Delete</th>
<th style="text-align: center;">Public Post</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;">
Edit
</td>
<td style="text-align: center;">
Edit
</td>
<td style="text-align: center;"></td>
</tr>
</tbody>
</table>
And in my Models folder I created Amsterdam.cs which looks like this:
namespace MyFirstWebsite.Models
{
public class Amsterdam
{
[Key]
public int Id { get; set; }
public string Details { get; set; }
public string Date_Posted { get; set; }
public string Time_Posted { get; set; }
public string Date_Edited { get; set; }
public string Time_Edited { get; set; }
public string Public { get; set; }
public int User_Id { get; set; }
}
}
And in my Controllers folder my HomeController looks like this:
public ActionResult Amsterdam()
{
return View();
}
[HttpPost]
public ActionResult Amsterdam(Amsterdam list)
{
string timeToday = DateTime.Now.ToString("h:mm:ss tt");
string dateToday = DateTime.Now.ToString("M/dd/yyyy");
if (ModelState.IsValid)
{
using (var db = new MainDbContext())
{
Claim sessionEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email);
string userEmail = sessionEmail.Value;
var userIdQuery = db.Users.Where(u => u.Email == userEmail).Select(u => u.Id);
var userId = userIdQuery.ToList();
var dbAmsterdam = db.Amsterdam.Create();
dbAmsterdam.Details = list.Details;
dbAmsterdam.Date_Posted = dateToday;
dbAmsterdam.Time_Posted = timeToday;
dbAmsterdam.User_Id = userId[0];
db.Amsterdam.Add(dbAmsterdam);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("", "Incorrect format has been placed");
}
return View();
}
I know I got close because my register does work but I can't get my CRUD for Amsterdam to work. When I click ok as shown in the screenshot (when I click on Ad Item):
https://i.stack.imgur.com/XsGws.png
I get an error
DbUpdateException was unhandled by user code
https://i.stack.imgur.com/I6kYP.png
It appears that EF is doing pluralization of your object name to define the table name in the database (from the error - Invalid object name dbo.Amsterdams).
If your table name is Amsterdam (singular, without the trailing "s"), then add this data annotation to your model class:
[Table("Amsterdam")]
public class Amsterdam
{
[Key]
public int Id { get; set; }
.....
}
And if you want to turn off that pluralization of table names completely, you can add this line to your MainDbContext class:
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
Below is the Model
public class M_ProjectType
{
public Int16 ProjectTypeID { get; set; }
public String ProjectType { get; set; }
public Boolean IsActive { get; set; }
public Decimal Cost { get; set; }
public String Description { get; set; }
public Boolean IsChecked { get; set; }
}
Below is View Model
public class VM_Project
{
public string[] SkillID { get; set; }
public List<M_ProjectType> ProjectType { get; set; }
}
Below is Get Action method. here I am getting the data for projects that will be sent to View Model
[HttpGet, Route("Project")]
public async Task<ActionResult> Project()
{
var projectTypes = (await _projectTypes.ProjectTypesList()).Value;
var list = new List<M_ProjectType>();
foreach (var item in projectTypes)
{
list.Add(new M_ProjectType
{
Cost = item.Cost,
Description = item.Description,
IsActive = item.IsActive,
IsChecked = false,
ProjectType = item.ProjectType,
ProjectTypeID = item.ProjectTypeID
}
);
}
var project = new VM_Project
{
ProjectType = list
};
return View(project);
}
Below is Razor View
#foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<input type="hidden" value="#item.ProjectTypeID" name="ProjectTypeID" />
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => item.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => item.ProjectTypeID)
</td>
<td style="width:10%">#item.ProjectType</td>
<td style="width:80%">#item.Description</td>
<td style="width:5%"><b>$#item.Cost</b></td>
</tr>
</tbody>
</table>
}
Below is Post Action Method
[HttpPost, Route("Project")]
public ActionResult Project(VM_Project project)
{
return View();
}
Question: I am getting project.ProjectType = null. Any suggestion why
this is happening ?
I would recommend using EditorTemplates.
Create a folder named EditorTemplates in you Views/Shared direcotry.
Create a partial view based on your type i.e. M_ProjectType.cshtml
Put your markup that you use in foreach loop in M_ProjectType.cshtml file
#model M_ProjectType
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => i.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => i.ProjectTypeID)
</td>
<td style="width:10%">#Model.ProjectType
#Html.HiddenFor(i=>i.ProjectType)
</td>
<td style="width:80%">#Model.Description</td>
<td style="width:5%"><b>$#Model.Cost</b></td>
</tr>
</tbody>
Then render your editor template in your form like (note: no foreach loop)
#Html.EditorFor(m=>m.ProjectType)
You should get correct model binded to your html elements back in controller.
Try this:
#foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => item.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => item.ProjectTypeID, new { #Value = item.ProjectTypeID})
</td>
</tr>
</tbody>
</table>
}