I am working on displaying data in a separate div and when I pass my javascript function data it does not fire onclick. It works when I use data from the parent but not after I cast the data from the parent into a child and try to pass the JS function with that data.
##view##
#using WebApplication2.Models
#model IEnumerable<WebApplication2.Models.OBJECT>
#{
ViewBag.Title = "CompAndMon";
}
<script>
//this function does not fire when called
function setO(OfficeLocation,Name,Email,Phone,NumComputers,NumMonitors) {
var text = "Primary Contact Name " + Name+"\n Primary Contact Email: " +Email +"\n Primary Contact Phone: " +Phone +"\n Number of Computers: " +NumComputers +"\n Number Of Monitors: " +NumMonitors;
var location = "Office Location: " + OfficeLocation;
document.getElementById("Nametag").innerHTML = location;
return document.getElementById("OCM").innerHTML = text;
}
//this function does not fire when called
function setComputer(lastS) {
var text = "you selected Item No: " + lastS;
return document.getElementById("OCM").innerHTML = text;
}
//this function operates correctly
function setMonitor(id) {
var text = "you selected Item No: " + id;
return document.getElementById("OCM").innerHTML = text;
}
</script>
#foreach (var item in Model)
{
if (#item.Type == 1)
{
var office = item as Office;
var loc = #office.OfficeLocation;
var Name = #office.Name;
var email = #office.Email;
var phone = #office.Phone;
var mons = #office.NumMonitors;
var comps = #office.NumComputers;
<p><a onlick="setO(#loc,#Name,#email,#phone,#comps,#mons)">#office.Name</a></p>
}
else if (#item.Type == 2)
{
var computer = item as Computer;
<p> <a onclick="setComputer(#computer.LastUser)">#item.Name1</a></p>
}
else
{
var monitor = item as Monitor;
<p> <a onclick="setMonitor(#item.ID)">#item.Name1</a></p>
}
}
<h2 id="Nametag" style="text-align:center"></h2>
<div id ="OCM"class="row">
Select a computer or monitor and the information about the de will be displayed here.
</div>
and here are the class models that the view uses
##OCM.cs##
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.Models
{
public abstract class OBJECT
{
public int ID { get; set; }
public int Type { get; set; }
public string Name1 { get; set; }
}
public class Office:OBJECT
{
public string OfficeLocation { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int NumComputers { get; set; }
public int NumMonitors { get; set; }
}
public class Computer:OBJECT
{
public String LastUser { get; set; }
public String Name { get; set; }
public int NumMonitors { get; set; }
public String TotalHDSpace { get; set; }
public String FreeHDSpace { get; set; }
public int NumUpdates { get; set; }
}
public class Monitor:OBJECT
{
public String Manufacturer { get; set; }
public String ModelID { get; set; }
public String SerialNum { get; set; }
public int HoursON { get; set; }
public String LastTestTime { get; set; }
public String LastTestType { get; set; }
}
}
When I inspect the element chrome it shows that the data is being passed the the function, but it doesn't run so I am not sure what to do. any help would be appreciated
Here shows that the data was passed to the JS functions when I inspect the element
You use string without quote
setComputer('ted') or setComputer(\"ted\") and not setComputer(ted)
this is the same for email and other arguments
I found that I misspelt onclick in the setO() call and needed to pass my razor variables to the javascript function in single quotes.
Related
I have a object that I am trying to pass to my C# controller. All the properties get populated except the list I have is always count =0. I have tried setting the header to content-type/json and Json.stringify. Also for testing I am returning the product list from another call so I know that returns a list of products to my view that is formatted correctly.
example for creating request
var request =
'Id':null,
...
... rest of data is here standard properites
...
'Products':productlist
for product list I am currently using the return value from a call that returns a List
return $http.post('api/Enty/Save', request )
.error(function (data, status, headers, config) {
errorLog('error: ' + data);
});
public class Person:IPerson
{
[Required]
public int Id { get; set; }
[MaxLength(90)]
public String Address1 { get; set; }
[MaxLength(90)]
public String Address2 { get; set; }
[MaxLength(40)]
public String Address3 { get; set; }
[MaxLength(40)]
public String City { get; set; }
[MaxLength(2)]
public String State { get; set; }
[MaxLength(40)]
public String Province { get; set; }
[MaxLength(10)]
public String Zip { get; set; }
public IList<IProduct> Products { get; set; }
}
[HttpPost()]
public Response Save(person r)
{}
UPDATE
If I make it List instead of IList it works. Any ideas why?
Turns out the issue was not the Ilist but the Iproduct. I just changed to a concrete class for that property
I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.
I made a form where user can enter all details. Like a fill up form. After filling up form. When user click on Save button it should be automatically move to other action method in same controller. And must show data in GRID VIEW in MVC. Where in grid view user can update and save all data which he entered while filling up the form.
I used DB first approach. And make a view model class. Here is the code of View Model class.
public class ViewModel
{
[Required(ErrorMessage = "Please Enter Prodcut Name")]
[DisplayName("Product Name")]
public string Product_Name { get; set; }
[Required(ErrorMessage = "Please Choose Category")]
public int SelectedValue { get; set; }
[Required(ErrorMessage = "Enter Price")]
[DisplayName("Enter Price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Choose Picture")]
[DisplayName("Choose Picture")]
public string Picture { get; set; }
[Required(ErrorMessage = "Choos Country")]
public Nullable<int> Country_ID { get; set; }
[Required(ErrorMessage = "Choose Type")]
[DisplayName("Choose Product Type")]
public string Product_Type { get; set; }
public SelectList CategoryList { get; set; }
public SelectList CountryList { get; set; }
[Required(ErrorMessage = "Select Date")]
public DateTime Date { get; set; }
}
Controller Code
ProductionEntities DBContext = new ProductionEntities();
public ActionResult Index()
{
ViewModel model = new ViewModel();
List<tblCategory> CategoryList = DBContext.tblCategories.ToList();
model.CategoryList = new SelectList(CategoryList, "Category_ID", "Category_Name");
List<tblCountry> CountryList = DBContext.tblCountries.ToList();
model.CountryList = new SelectList(CountryList, "Country_ID", "Country_Name");
return View(model);
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
//ViewModel v = new ViewModel();
//if (image1!=null)
//{
// model.Picture = new byte[image1.ContentLength];
// image1.InputStream.Read(model.Picture, 0, image1.ContentLength);
//}
List<tblCategory> CategoryList = DBContext.tblCategories.ToList();
model.CategoryList = new SelectList(CategoryList, "Category_ID", "Category_Name");
List<tblCountry> CountryList = DBContext.tblCountries.ToList();
model.CountryList = new SelectList(CountryList, "Country_ID", "Country_Name");
if (!ModelState.IsValid)
{
tblProduct product = new tblProduct();
product.Category_ID = model.SelectedValue;
product.Country_ID = model.Country_ID;
product.Price = model.Price;
product.Product_Name = model.Product_Name;
product.Date = model.Date;
product.Picture = model.Picture;
product.Product_Type = model.Product_Type;
try
{
DBContext.tblProducts.Add(product);
DBContext.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
return View(model);
}
You should follow P-R-G (Post-Redirect-Get) pattern. After successfully saving the record, send a redirect response to the browser which will issue a totally new GET request to the action method which renders the tabular data.
DBContext.tblProducts.Add(product);
DBContext.SaveChanges();
return RedirectToAction("List");
and in your List action method you will read the records needed for the tabular data and render it in it's view.
I am using openweather api to get weather data.when i enter the city name the server returns a json data I need to know how to handle the data and i need to display the data inside a div
function loadweather() {
var q = document.getElementById("in").value;
var appid = document.getElementById("appid").value;
var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + q + '&appid=' + appid;
$.getJSON(url, function(data) {
console.log(data)
});
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<input type="text" id="in" value="New Delhi"/>
<input type="hidden" id="appid" value="086a3e2bd775aac95a9b096b5233f049">
<button id="go" onclick="loadweather()">Search</button>
<div id="disp"></div>
You can access the data You got as an object. In your case the object will be as shown below.
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
You can access it script itself as shown below.
$.getJSON(url, function (data) {
$('#disp').html('Temperature:' + data.main.temp + 'deg Fahrenheit' + 'Pressure:'+ data.main.pressure)
});
I m trying to pass a object to view with viewbag and pass it to javascript parameter in the view
But when comes to assign object to script value it looks like string likes its namespace
in controller:
public ACCIDENT_REPORTS getFilledReportWithEntitiesById(int accidentReport_id)
{
ACCIDENT_REPORTS report = new ACCIDENT_REPORTS();
report = context.ACCIDENT_REPORTS.Include("ACCR_ENTITIES").Where(a => a.ID == accidentReport_id).FirstOrDefault();
return report;
}
ViewBag.Report = DatabaseContext.Current.AccidentReportingRepository.getFilledReportWithEntitiesById(id); //its okey, all data in viewbag
in view:
<script>
debugger
var data = '#ViewBag.Report';
</script>
// in debugger value looks like; var data = 'Application.Database.ACCIDENT_REPORTS;
Why it looks like string ? how can I pass contents of viewbag to javascript value
here is my entity object return type:
public partial class ACCIDENT_REPORTS
{
public ACCIDENT_REPORTS()
{
this.ACCR_ENTITIES = new HashSet<ACCR_ENTITIES>();
}
public decimal ID { get; set; }
public decimal FACILITY_ID { get; set; }
public Nullable<System.DateTime> START_DATE { get; set; }
public Nullable<System.DateTime> END_DATE { get; set; }
public string TITLE { get; set; }
public Nullable<decimal> ACCIDENT_TYPE { get; set; }
public Nullable<decimal> REPORTED_UNDER { get; set; }
public Nullable<decimal> SEVESOII_STATUS { get; set; }
public Nullable<decimal> INDUSTRIAL_ACTIVITY { get; set; }
public string REASON_FOR_REPORTING { get; set; }
public string ACCIDENT_DESCRIPTION { get; set; }
public string SITE_DESCRIPTION { get; set; }
public string UNIT_DESCRIPTION { get; set; }
public string CAUSES_OF_ACCIDENT { get; set; }
public string CONSEQUENCES { get; set; }
public string EMERGENCY_RESPONSE { get; set; }
public string LESSONS_LEARNED { get; set; }
public string ACCIDENTS_INVOLVING { get; set; }
public Nullable<decimal> REPORT_STATUS { get; set; }
public virtual ICollection<ACCR_ENTITIES> ACCR_ENTITIES { get; set; }
}
}
What is the type returned by getFilledReportWithEntitiesById()?
Presumably, it's a Application.Database.ACCIDENT. All the view engine does is invoke .ToString() on what it's given. And the default implementation for .ToString() on any reference type (any child of object basically) is to return the type name.
If you want a custom string representation of your type, then that type needs to override .ToString(). For example:
public override string ToString()
{
return string.Format("{0} - {1}", ID, Name);
}
If the object has an ID property and a Name property then its string representation would then be those values separated by a hyphen (with spaces in between). However you want to structure the string representation of your object would be done within this method.
Conversely, if you don't want it to be a string, but want the JavaScript code to use it as an object, then you want to serialize it to JSON. Something like this:
var data = #Json.Encode(ViewBag.Report);
(You might need to tweak that a little bit, I don't have an environment handy to test it. But you get the idea... To use it as an object in JavaScript code it needs to be serialized to a JavaScript object literal.)
this is the real answer
#Html.Raw(Json.Encode(Model.PlaceStatistic.ToArray()))