Actually my ajax code is working perfectly if I remove that one particular string variable
I am calling ajax, then server will pick some data from SQL Server and store it into string variable. Every variable returning perfectly except that one variable. When I check console, it return exception "System.IndexOutOfRangeException"
Here is my ajax code
$('.list-of-link').on('click', 'a', function (e) {
e.preventDefault();// add this line
alert($(this).html());
//window.location.replace("ReportTotalSalesPivot.aspx");
var userFileName = $(this).html();
$.ajax({
url: 'SavedReports.aspx/getReportDetails',
method: 'post',
contentType: 'application/json',
data: '{userFileName:"' + userFileName + '"}',
dataType:'json',
success: function (data) {
alert('success : ReportData = ' + data.d.ReportData);
},
error: function (error) {
alert('Please Call Administrator');
}
})
})
WebMethod code
[WebMethod]
public static SavedReport getReportDetails(string userFileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData,ReportFilter,FromDate,ToDate,SelectedData,SelectedCoulmn,SelectedRow,HiddenTableRecord ToDate FROM [HQWebMatajer].[dbo].[ReportSave] where UserID=#UserID and UserFileName=#UserFileName";
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#UserFileName", userFileName);
con.Open();
SavedReport savedReport = new SavedReport();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
byte[] binaryString = (byte[])rd["ReportData"];
savedReport.ReportData = Encoding.UTF8.GetString(binaryString);
savedReport.ReportFilter = rd["ReportFilter"].ToString();
savedReport.FromDate = rd["FromDate"].ToString();
savedReport.ToDate = rd["ToDate"].ToString();
savedReport.SelectedData = rd["SelectedData"].ToString();
savedReport.SelectedColumn = rd["SelectedCoulmn"].ToString();
savedReport.SelectedRow = rd["SelectedRow"].ToString();
savedReport.HiddenTableRecord = rd["HiddenTableRecord"].ToString();
}
return savedReport;
}
}
Error occur in the last variable HiddenTableRecord
The following record is actual record for HiddenTableRecord from SQL Server tq.StoreID$$$ IN('1001')$$$
SavedReport class code
public class SavedReport
{
public string UserID { get; set; }
public string ReportName { get; set; }
public string UserFileName { get; set; }
public string ReportData { get; set; }
public string ReportFilter { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
public string SelectedData { get; set; }
public string SelectedColumn { get; set; }
public string SelectedRow { get; set; }
public string HiddenTableRecord { get; set; }
}
Error msg
{Message: "HiddenTableRecord",…}
ExceptionType:"System.IndexOutOfRangeException"
Message:"HiddenTableRecord"
Note
If I comment this line savedReport.HiddenTableRecord = rd["HiddenTableRecord"].ToString();. Error is not occurring and it returns all the records what I expect
The problem comes because your SqlDataReader doesn't contains "HiddenTableRecord"
Maybe there is an issue in your SqlRequest (a comma is missing in your example between HiddenTableRecord and ToDate):
"select ReportData,ReportFilter,FromDate,ToDate,SelectedData,SelectedCoulmn,SelectedRow,HiddenTableRecord , ToDate FROM [HQWebMatajer].[dbo].[ReportSave] where UserID=#UserID and UserFileName=#UserFileName";
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
all works fine in front end side , all with values and all well but wont arrive as class data and if i send a string in body they will arrive regular and work and method get all works i dont know what happening to this
this in C# asp.net
[HttpPost]
[Route("api/NewPost/Add")]
public IHttpActionResult addPost([FromBody] Post newPost)
{
try
{
string str = $"INSERT INTO [Post]([userId],[title], [description], [photos], [catalogType],[postDate],[typePost]) VALUES({newPost.userId},'{newPost.title}','{newPost.description}','{newPost.photos}','{newPost.catalogType}','{newPost.postDate}','{newPost.typePost}')";
SqlConnection con = connectionDb.connectToDb();
SqlCommand comm = new SqlCommand(str, con);
con.Open();
comm.ExecuteReader();
con.Close();
return Ok(true);
}
catch (Exception err)
{
return Ok(err.Message);
}
return Ok(false);
}
here what in js and all with value
fetch('http://localhost:55866/api/NewPost/Add',{
method:'POST',
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({postId:-1,userId,title,description,photos,catalogType:route.params.catalog,postDate:null,typePost})
}).then(r=>r.json()).then(data=>{
if(data === true){
setAlertSucessfully(true)
}
}
).catch(err=>console.log('error :' + err.message))
here the class i tried to public all and wont work too arrive as null with problem
$exception {"Object reference not set to an instance of an object."} System.NullReferenceException
public class Post
{
// automatic post Id
public int postId;
public int userId;
public string title;
public string description;
public string photos;
public string catalogType; //dog - cat - other
public DateTime postDate;
public string typePost; //advice - ask - photo
```
public Post(int postId,int userId, string title, string description, string photos, string catalogType, DateTime postDate, string typePost)
{
if (postId != -1)
this.postId = postId;
else
this.postId = -1;
Console.WriteLine(postId);
this.userId = userId;
this.title = title;
this.description = description;
if (photos == null)
this.photos = null;
else
this.photos = photos;
this.typePost = typePost;
this.catalogType = catalogType;
this.postDate = DateTime.Now;
}
public override string ToString()
{
return $"{postId} {userId} {title} {description} {photos} {typePost} {catalogType} {postDate}";
}
}
at first fix Post class by adding getter-setters
public class Post
{
public int postId {get; set;}
public int userId {get; set;}
public string title {get; set;}
..... and so on
}
and try this code
fetch('http://localhost:55866/api/NewPost/Add',{
method:'POST'
body: { newPost: { postId:3,
userId:4,
title: "title",
description:"desciption",
photos:null,
catalogType:"catalog",
postDate:new Date().toISOString(),
typePost:null}}
}).then(r=>r.json()).then(data=>{ .... your code
and action
[Route("~/api/NewPost/Add")]
public IActionResult addPost([FromBody] Post newPost)
.....
I want to update values in my database. to make sure my script was working and to send the values I created a POST method to check and the values are coming.
My question now is with the values coming to the method, how to update or save my values in the database?
Controller:
[HttpPost]
public JsonResult EditPost(Programa_Cor_Info_Status statusData)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
return Json(status, JsonRequestBehavior.AllowGet);
}
I tried using db.savechanges on my controller but to no avail.
Could someone help me with an example?
Thanks
------------Update-----------------------------------------
[HttpPost]
public ActionResult EditPost(Programa_Cor_Info_Status statusData, int ID_Status)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
var q = db.Programa_Cor_Info_Status.Where(m => m.ID_Info == ID_Status).FirstOrDefault();
q.ID_Info = ID_Status;
db.Entry(q).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);
}
namespace Balu0._1.Models
{
using System;
using System.Collections.Generic;
public partial class Programa_Cor_Info_Status
{
public int ID_Info { get; set; }
public int ID_Programa { get; set; }
public int ID_Linha_Cor { get; set; }
public string Status { get; set; }
public string Obs { get; set; }
}
}
If you stll don't have, in your view add hidden model field with ID_Info value.
Change your action to this:
public ActionResult EditPost(Programa_Cor_Info_Status statusData)
{
var existItem = db.Programa_Cor_Info_Status.Find(statusData.ID_Info);
// or if you dont have a proper primary key you can try
var existItem = db.Programa_Cor_Info_Status
.Where( i=> i.ID_Info== statusData.ID_Info).FirstOrDefault();
if (existItem != null)
{
db.Entry(existItem).CurrentValues.SetValues(statusData);
var result = db.SaveChanges(); // if result==0 then error
} else ...error
return Json(statusData, JsonRequestBehavior.AllowGet);
}
thanks for the help i already got !!!
db.Entry(status).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);
I have several input fields on my page. Now on button click event, I want to call a WCF service which is responsible for storing data into the database.
<asp:Button runat="server" ID="btnCreateApplyTemplate" Text="Create" Style="text-transform: uppercase; color: #fff;"
CssClass="btn lr-small-btn-template lr-btn-success" ClientIDMode="Static" OnClientClick="return SaveMockTestData(this);" />
page.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager manager = ScriptManager.GetCurrent(Page);
ServiceReference srMockTest = new ServiceReference("~/WCFSERVICES/MockTest.svc");
manager.Services.Add(srMockTest);
ScriptReference dd1 = new ScriptReference("~/SvcToDb/JsMocktest.js");
manager.Scripts.Add(dd1);
}
}
Now let me show you what is inside the file, JsMocktest.js
(function (global, undefined) {
var mocktest = {};
var mockTestData = {};
function SaveMockTestData(args) {
if (args.value == "Save Template") {
mockTestData.TemplateName = mocktest.txtTemplateName.value;
mockTestData.TotalMarks = mocktest.txtTotalMarks.value;
mockTestData.ExamDuration = mocktest.txtDuration.value;
mockTestData.TotalQuestion = mocktest.txtTotQuestion.value;
//question types
let chkisMcq = mocktest.chkisMcq.checked;
let txtMcqTypePostvMark = mocktest.txtMcqTypePostvMark.value;
let txtMcqTypeNegtvMark = mocktest.txtMcqTypeNegtvMark.value;
let chkisNonMcq = mocktest.chkisNonMcq.checked;
let txtNonMcqTypePostvMark = mocktest.txtNonMcqTypePostvMark.value;
let txtNonMcqTypeNegtvMark = mocktest.txtNonMcqTypeNegtvMark.value;
var questionTypes = {
qtype: []
};
if (chkisMcq) {
questionTypes.qtype.push({
"isMcq": true,
"PostiveMarks": txtMcqTypePostvMark,
"NegetiveMark": txtMcqTypeNegtvMark,
});
}
if (chkisNonMcq) {
questionTypes.qtype.push({
"isMcq": false,
"PostiveMarks": txtNonMcqTypePostvMark,
"NegetiveMark": txtNonMcqTypeNegtvMark,
});
}
debugger;
mockTestData.TotalQuestionType = questionTypes;
var table = $('#tableContainer').tableToJSON({
ignoreColumns: [3]
}
);
mockTestData.TotalSections = table;
mockTestData.CalculatorTupe = mocktest.ddlCalcType.value;
mockTestData.IsAutoSave = mocktest.chkIsAutoSave.checked;
mockTestData.IsQuizPause = mocktest.chkCanPause.checked;
mockTestData.IsMultilingualSupport = mocktest.chkIsMultLingual.checked;
mockTestData.ExamInstruction = mocktest.chkExamInstruction.checked;
mockTestData.ExamInstructionId = mocktest.ddlExamInstruction.value;
var IMockTetst = new WcfAjaxServices.IMockTest();
debugger;
IMockTetst.InsertTemplateData(mockTestData, function (result, context, OnSuccess) {
}, function (error, context, OnError) {
//toastify("error", "ppp", "System Error", "toast-bottom-right", true);
}, null);
}
return false;
}
global.$MockTestControlID = mocktest;
global.SaveMockTestData = SaveMockTestData;
})(window);
Now here is the Service,
public class MockTest:IMockTest
{
readonly BO_MockTest _objBoMockTest = new BO_MockTest();
BL_MockTest objBL_BusinessPartners = new BL_MockTest();
public int InsertTemplateData(TemplateData data)
{
_objBoMockTest.Flag = "1";
_objBoMockTest.TemplateName = data.TemplateName;
_objBoMockTest.TotalMarks = data.TotalMarks;
_objBoMockTest.ExamDuration = data.ExamDuration;
_objBoMockTest.TotalQuestions = data.TotalQuestion;
//_objBoMockTest.TotalQuestionTypes = data.TotalQuestionType;
//_objBoMockTest.TotalSections = data.TotalSections;
_objBoMockTest.CalculatorType = data.CalculatorTupe;
_objBoMockTest.IsAutoSave = data.IsAutoSave;
_objBoMockTest.IsQuizPause = data.IsQuizPause;
_objBoMockTest.IsMultilingualSupport = data.IsMultilingualSupport;
_objBoMockTest.IsContainExamInstruction = data.ExamInstruction;
_objBoMockTest.ExamInstructionId = data.ExamInstructionId;
return 0;
}
}
here is the interface,
[ServiceContract(Namespace = "WcfAjaxServices")]
public interface IMockTest
{
[OperationContract]
int InsertTemplateData(TemplateData data);
}
[DataContract]
public class TemplateData
{
[DataMember]
public string TemplateName { get; set; }
[DataMember]
public string TotalMarks { get; set; }
[DataMember]
public string ExamDuration { get; set; }
[DataMember]
public string TotalQuestion { get; set; }
[DataMember]
public string TotalQuestionType { get; set; }
[DataMember]
public string TotalSections { get; set; }
[DataMember]
public string CalculatorTupe { get; set; }
[DataMember]
public bool IsAutoSave { get; set; }
[DataMember]
public bool IsQuizPause { get; set; }
[DataMember]
public bool IsMultilingualSupport { get; set; }
[DataMember]
public bool ExamInstruction { get; set; }
[DataMember]
public string ExamInstructionId { get; set; }
}
Now I dont have any clue how to map my json object i.e mockTestData with TemplateData and more overover
how to call int InsertTemplateData(TemplateData data); this method from my javascript code..
Edit In My Post
I just changed my WCF method like this,
[OperationContract]
int InsertTemplateData();
instead of using
[OperationContract]
int InsertTemplateData(TemplateData data);
and
public class MockTest:IMockTest
{
readonly BO_MockTest _objBoMockTest = new BO_MockTest();
BL_MockTest objBL_BusinessPartners = new BL_MockTest();
public int InsertTemplateData()
{
TemplateData data = new TemplateData();
_objBoMockTest.Flag = "1";
_objBoMockTest.TemplateName = data.TemplateName;
_objBoMockTest.TotalMarks = data.TotalMarks;
_objBoMockTest.ExamDuration = data.ExamDuration;
_objBoMockTest.TotalQuestions = data.TotalQuestion;
//_objBoMockTest.TotalQuestionTypes = data.TotalQuestionType;
//_objBoMockTest.TotalSections = data.TotalSections;
_objBoMockTest.CalculatorType = data.CalculatorTupe;
_objBoMockTest.IsAutoSave = data.IsAutoSave;
_objBoMockTest.IsQuizPause = data.IsQuizPause;
_objBoMockTest.IsMultilingualSupport = data.IsMultilingualSupport;
_objBoMockTest.IsContainExamInstruction = data.ExamInstruction;
_objBoMockTest.ExamInstructionId = data.ExamInstructionId;
return 12;
}
}
and called like this,
IMockTetst.InsertTemplateData(function (result, context, OnSuccess) {
debugger;
}, function (error, context, OnError) {
//toastify("error", "ppp", "System Error", "toast-bottom-right", true);
}, null);
and doing so I am getting, the result as expected. So it means there is a problem with mockTestData which I am passing from javascript and the TemplateData which is receiving it...
My question is how to map those two variables? I think there is an issue with mapping .. ?? Help needed please :)
It seems that you have resolved the issue that how to call WCF service from the Javascript code. The rest problem is how can we pass the parameter to method when using a JSON object.
Please refer to the example.
<script>
function Calculate() {
var product = { "Name": "apple", "Amount": 3, "Price": 4.23 };
CostService.CostOfProducts(product, function (result) {
console.log(result)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Content/CostService.svc" />
</Services>
</asp:ScriptManager>
<div>
Calculate the total prices of the Products.
</div>
<input type="button" value="Price of 3 sandwiches" onclick="Calculate()" />
<br />
<span id="additionResult"></span>
</form>
</body>
SVC file.
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
[OperationContract]
public double CostOfProducts(Product product)
{
return product.Amount * product.Price;
}
}
[DataContract]
public class Product
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Amount { get; set; }
[DataMember]
public double Price { get; set; }
}
Feel free to let me know if there is anything I can help with.
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 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.