Display a List of Tuples in a C# cshtml View - javascript

I have tried a few ways to get this Tuple list to display in my cshtml view as uploadModel.ErrorsList but have had no luck, this only displays the type of object the Errorslist (Tuple List int, string, string) is, the ErrorMessages (strings) do show the correct values on the screen. Here is my view:
#using Custom.Website.Areas.Custom.Models
#model Custom.Website.Areas.Custom.Models.ExcelUploadModel
<style type="text/css">
#ExcelUploadForm {
text-align: center;
}
</style>
<div id="ExcelUploadForm" title="Excel Upload Results">
<h2 id="requireReUpload" style="color:darkred">Please fix the following errors and reupload:</h2>
<h2 id="uploadSuccess" style="color:green">Your Upload was successful. #Model.UploadedRowCount tickets updated.</h2>
<div>Editable fields: Transporter Ticket #,Transporter, Driver, Truck, AFE #, Water Type, Quantity, Operator Job #, Lease.</div>
<div>
<ul id="uploadErrors"></ul>
</div>
<button class="backButton">Back</button>
</div>
<script type="text/javascript">
document.getElementById("requireReUpload").style.display = 'none';
document.getElementById("uploadSuccess").style.display = 'none';
$(document).ready(function () {
$('#uploadErrors').append('<li>#Model.ErrorMessage</li>');
$('#uploadErrors').append('<li>#Model.ErrorsList</li>');
//This function checks if the Error list contains any value.
function excelUploadMessage() {
// If Error List has nothing, display Success
if ($('ul#uploadErrors:not(:has(li)')) {
document.getElementById("uploadSuccess").style.display = 'block';
} // Otherwise, display reupload message
else {
document.getElementById("requireReUpload").style.display = 'block';
}
}
excelUploadMessage();
});
$('.backButton').click(function () {
window.history.back();
});
</script>

instead of :
$('#uploadErrors').append('<li>#Model.ErrorsList</li>');
create a for loop:
#foreach (var tupleErr in Model.ErrorsList){
<text>$('#uploadErrors').append('<li>#tupleErr.Item1 #tupleErr.Item2 #tupleErr.Item3</li>');</text>
}
sorry did not validate the syntax; but the idea is that you need to iterate over the list, then have an append jQuery statement for each item in the list. Keep in mind you can access the tuple items by the properties as "Itemx" .

Related

Accessing the session data in bootstrap wizard

I'm trying to create a customer survey form and I used a bootstrap wizard to navigate through the questions.
So here in the first section, there is a dropdown list for users to select the language.
When the user selects a language I wrote a javascript to get the selected value and pass to the controller and assign it to the session.
So in the next section, I want to show the questions by the selected value which is now stored at the session.
Don't know the method I tried to create this is right or wrong but I realize that it's only read the session data on load.
So is there any way to do this change with the selected value from the first dropdown?
This is the first step
<form action="" id="wizard">
<!-- SECTION 1 -->
<h4></h4>
<section>
<h3>Please select the Language</h3>
<div class="form-row center">
<div class="form-holder center "> #Html.DropDownListFor(model => model.Language, new SelectList(new[] { "English", "සිංහල", "தமிழ்" }),"Please Select the Language", new { #class = "form-control js-dropdown",Id ="DropLanguage" }) </div>
</div>
</section>
This is the script that collects the selected value and passes to the controller to set it to the session
< script type = "text/javascript" >
$(document).ready(function () {
$("#DropLanguage").on("change", function () {
// This is the jQuery way of finding selected option's text
var myVar = $(this).find("option:selected").text();
// Post the value to your server. You should do some error handling here
$.post("/MainDetails/SetSession", {
myVariable: myVar
});
});
}); <
/script>
This is the controller that set the value of the session.
[HttpPost]
public ActionResult SetSession(string myVariable) {
// Set to Session here.
Session["SelectedLanguage"] = null;
if (myVariable == "English") {
Session["SelectedLanguage"] = "Secondary";
} else if (myVariable == "සිංහල") {
Session["SelectedLanguage"] = "Primary";
} else if (myVariable == "தமிழ்") {
Session["SelectedLanguage"] = "Third";
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
So in the next section I tried this,
#if (#Session["SelectedLanguage"].ToString() == "Primary")
{
<h3>Customer Details</h3>
}
else if (#Session["SelectedLanguage"].ToString() == "Secondary")
{
<h3>Customer Details - Language 2</h3>
}
But this if not triggered . it's only triggered with the form load.

If HTML response is null, display alternate content

My api call returns html, but if that html is empty e.g. I get a console html response of "", I want to display a default message using knockout. So I'm guessing that it needs to recognise that "" is empty and then display my alternate content.
View model -
var MyText = ko.observable();
var company = shell.authenticatedCompany();
hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) {
MyText(data);
});
return {
MyText: MyText
};
View -
<section class="help-text">
<div class="flex-container">
<div class="flex-item" data-bind="html: MyText">This is my alternate message if the html response is ""</div>
</div>
</section>
There are a few ways you could go about it. Personally I like to keep as much code out of the markup as possible so I would check your response data in the api callback and set it there. No need to create messy looking data bindings if you just update the observable appropriately.
hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) {
if(!data) {
MyText("This is my alternate message...");
}else{
MyText(data);
}
});
If you need to preserve what the api call actually returned you could place the logic in a computed instead, and bind to that.
One way to achieve this is to use a computed observable to determine which set of html to display:
https://jsfiddle.net/dw1284/ucnewzwo/
HTML:
<section class="help-text">
<div class="flex-container">
<div class="flex-item" data-bind="html: ItemHtml()"></div>
</div>
</section>
JavaScript:
function ViewModel() {
var self = this;
// Html populated from API call
self.MyText = ko.observable('');
// Default Html
self.Default = ko.observable('This is my alternate message if the html response is ""');
// Computed observable chooses which HTML to display (bind this to view)
self.ItemHtml = ko.computed(function() {
if (!self.MyText() || self.MyText() === '') {
return self.Default();
} else {
return self.MyText();
}
});
}
ko.applyBindings(new ViewModel());

How to add Contact List data into PhoneGap ListView

I have a javascript function which will read the device ContactList and add them into a javascript array.In my HTML page i have taken a listview.Now as per my requirement i have to add these array data into the listview by jquery dynamically which i am not able to do .I am not able to see anything on the screen of the mobile on launching the app..
Here is my javascript code to read from Mobile's contact list..
function onDeviceReady() {
// specify contact search criteria
var options = new ContactFindOptions();
options.filter=""; // empty search string returns all contacts
options.multiple=true; // return multiple results
filter = ["displayName"]; // return contact.displayName field
// find contacts
navigator.contacts.find(filter, onSuccess, onError, options);
}
var names = [];
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for (var i=0; i<contacts.length; i++) {
if (contacts[i].displayName) { // many contacts don't have displayName
names.push(contacts[i].displayName);
}
}
alert('contacts loaded');
}
and here is my HTML listview..
<div data-role="page" id="home" data-theme="c">
<div data-role="content">
<div id="header" class="header">
<h1>Contact Directory</h1>
</div>
<ul data-role="listview" id="contactlist" data-theme="a">
</ul>
</div>
</div>
So, My question is how can i add the array values into the listview by jquery dynamically..
Thanks..
Couple of ways, but here is one way.
Create a simple string variable to hold your LIs.
Loop over names and append to the string <li> + names[x] + </li> where X is your loop counter.
Use jQuery to get the UL dom and then do .html(s) where s is your string.
Basically you are injecting <li>...</li><li>...</li> into your UL.
The last step is to refresh the list view so jQuery displays it correctly. This is done with the refresh API, defined here: http://api.jquerymobile.com/listview/#method-refresh

Partial view with ajax and jQuery UI.Dialog

I am using a standard MVC4 EF5 setup and have a standard view which loads data from the db onto a table.
At the start of the table I have a column for each record with an Add button. The functionality I want is to click the button, popup a model dialog box with a form and add something to the item in the grid that was clicked (a 1 to many).
Lets say I have a list of vans available shown in the list. And when I click the add button beside the particular van where I want to add a passenger, I want a popup to show that allows me to type the details of the passenger so they can be assigned to that van.
I think I am over complicating this. But my brain is fried. I tried partial views with ajax. I tried jQuery UI.Dialog. Im just lost. I am trying to figure out how to find the id of the record I clicked (given the buttons are all generated by a for each loop in the view as normal and numbering them 1 to X does not tell me the id of the record I clicked). So even if I get the popup showing, I wont know which van to assign the passenger to.
If your woundering where the passenger list is coming from, its another table. And effectively any passenger can be assigned to any van. Its hypothetical.
Im actually working on a document generator and so there is a many to many relationship between document parts and documents (a given document part, can appear or belong to many documents, and a document can contain many document parts). I know its messy, this is why I did not want to use the real example.
I'm thinking its maybe an easy enough problem to solve but I have been at it since Friday and the brain left home!
Edit: Adding Code:
Here is the main view: The main problem I am having with this is the way the grid is constructed. I think its partially razor, partially html, partially html helper, and partially javascript. I don't know which part is which, but I just need to get a popup to show for each button in the table, and to have an id I can assign values to. I cant figure out how to do it here.
Html.Grid(dbaccess().Where(c => something = something
).Select(o => new
{
Name = o.Name,
Comment = o.Comment,
Status = o.Status,
}
, "grdConfiguration", 0, htmlRowClass: (p) => (row++ % 2 != 0) ? "" : "oddRow"
, columns: new[]{
//THIS IS THE PROBLEM LINE BELOW .... It shows a button in the table, but...
//how do I make it unique. Is it even necessary to do so.
// How do I get the ID of the record at this location when this button is pressed.
//This is the code as originally posted: For context
new Helpers.GridColumn(value: (a) => "<input type=\"button\" class=\"btn\" id=\"BtnHello\" value=\"Add\" />"),
//for some reason when I try the following alternative as suggest by the answers so far - it doesn't work.
new Helpers.GridColumn(value: (a) => "<input type=\"button\" class=\"btn\" data-ThisId=\"#model.SomeId\" value=\"Add\" />"),
//THIS IS THE PROBLEM LINE ABOVE....
there is more columns but this button calls the jQuery...
On this view I also have some Div tags in which to load the partial... I can actually get this to popup. But that's about all I can do. And only when I click the first button in the table.
<div id='SomePopUp' style='display: none;'>
//#using (Html.BeginForm())
//{
// <div>
// <span class="display-label">Quantity: </span>
// <span class="display-field"><input type="text" id="txtQuantity" /></span>
// </div>
// <div>
// <span class="display-label">Comments: </span>
// <span class="display-field"><textarea rows="7"></textarea></span>
// </div>
//}
</div>
I also have a script section on this view with the code for the popup:
<script type="text/javascript">
$("#BtnHello").click(function ()
{
$("#SomePopUp").dialog(
{
resizable: false,
height: 400,
width: 400,
modal: true,
title:"add to {Some ID}:", //I want the id to show here so I know I have the record I want.
buttons:
{
Submit : function ()
{
$(this).dialog('Some Text');
},
Cancel: function ()
{
$(this).dialog('close');
}
}
});
});
</script>
I have a controller:
[HttpGet]
public ActionResult AddExtra(int id)
{
//Fairly sure I should be doing something with this id, but how do I get it from the button.
return PartialView();
}
And for the partial view I have
#model CM.ViewModels.AddExtraPackagesViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add Something</h3>
</div>
<div>
//I was using ajax here...
#*#using (Ajax.BeginForm("DoSomething", "Something", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-something"
}))
{
<div class="modal-body">
#Html.TextBoxFor(x => x.Quantity);
#Html.TextAreaFor(x => x.Comment);
</div>
<div class="modal-footer">
<button class="btn btn-success" id="submit">Save</button>
Close
</div>
}
</div>
I made a little view model too but...
public class AddExtraViewModel
{
public int Id { get; set; }
public string Quantity { get; set; }
public string Comment { get; set; }
}
I apologise if this is all over the place but I did not write the original code. There were about 7 other programmers here before me and I'm just struggling to get through it.
Any help would be appreciated.
I think you would want something like this (using jQuery and jQuery UI):
Controller:
public ActionResult SomeAction(int id) {
return View(new YourModel { Id = id });
}
Partial View:
#model YourProject.Models.YourModel
// Partial view content e.g. the form etc.
Your view:
/<!-- html etc. -->
<table>
<tr>
<td>Add</td>
</tr>
</table>
<script>
$(function(){
$(".add-button").click(function(){
var options = {
autoOpen: false
}
var dialog = $("<div>").dialog(options);
var id = $(this).data("theId");
dialog.load("the/url/to/the/controller/action", { id: id }, function(){
dialog.dialog("open");
dialog.find("form").submit(function(){
// do stuff
dialog.remove();
return false;
});
});
});
});
</script>
if you are building buttons in a forloop you don't want to define an id on the button. Duplicate id's on a view can cause lots of issues. Use a class on the buttons instead to trigger off of and use $(this) in your script to get details of the button that was clicked. To access buttons on a partial or on items that are added to your page after page load you need to tie the click event for that button to the document like this
$(document).on("click", ".btnDetails", function(){
//your script here
});
The other example uses "this" and shows how you can pass the id of the clicked button back to the controller. The controller will need to be a little different though
public PartialViewResult PopulatePartial(int ID){
var Model = //populate your model based on the passed id
return PartialView("PartialViewName", Model);
}

KendoUI grid for ASP.net MVC

I have a requirement of a search page in which I am using KendoUI grid to display the search result.
I have a textbox and button and if text is entered and on click event of button I hace to display the grid with the list of users matching to search result.
I am using ASP.net MVC and KENDOUI grid.
My View:
The search box and button:
<div id="SearchSection">
<input type="text" id="txtSearch" class="k-textbox"/>
<button class="k-button"id="btnSearch" style="width:150px">Search</button>
</div>
The KendoUI grid
<div id="ADUserSection">
<div id="ADSearchedUser">
List of users in Active directory:
<div id="ADuserGrid">
#(Html.Kendo().Grid<ADUser>()
.Name("kADUser")
.Columns(columns =>
{
columns.Bound(p => p.UserLoginName);
columns.Bound(p => p.UserDisplayName);
})
.AutoBind(false)
.DataSource(ds =>
{
ds.Ajax()
.Read(read =>
{
read.Action("GetADUser", "ManageUsers")
.Data("AdditionalData");
});
})
)
)
</div>
</div>
My JavaScript Function:
<script>
$(document).ready(function () {
$("#ADUserSection").fadeOut(0);
$("#AvailableUserRoleSection").fadeIn()
});
var enterTest
$("#btnSearch").click(function () {
debugger;
enterTest = $("#txtSearch").val().trim();
if (enterTest == "") {
$("#ADUserSection").fadeOut();
}
else {
AdditionalData();
$("#ADUserSection").fadeIn();
var grid = $("kADUser").data("kendoGrid").dataSource.read({ searchText: enterTest });
//**Breaks at this Point**//
}
});
function AdditionalData() {
//$("#ADuserGrid").empty();
$("#ADuserGrid").fadeIn();
return {
searchText: enterTest
}
}
My Controller Action
public JsonResult GetADUser([DataSourceRequest] DataSourceRequest request, string searchText)
{
viewmodel.searchedADUser = model.GetUserFromAD(searchText);
return Json(viewmodel.searchedADUser.ToList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
On the button click event in javascript when I attach the grid to event I get the error the datasource read is not recognised.
Exact error is:
JavaScript runtime error: Unable to get property 'dataSource' of undefined or null reference
Please help me in that. any idea please share or if I am doing anything wrong in my above code please point out.
I am very new to KendoUi and MVC so please elaborate n yur explanation.
I got the above problem becosue of missing # before the grid name.
But Now I habe one more issue, even though I am follwing all the proper step.
In my above AdditionalData javascript function my parameter is not getting set set in the paaremeter
function AdditionalData() {
//$("#ADuserGrid").empty();
$("#ADuserGrid").fadeIn();
return {
searchText: enterTest
}
}
This searchText is not getting set even tough I am getting value in enterTest.
Any help will be of very great use. I am really stuck in this.
You're trying to access your grid with:
var grid = $("kADUser").data("kendoGrid");
$("kADUser") won't find any elements, because it's looking for a kADUser tag, and the .data() of an empty jQuery set is null.
As a result, when you try to access grid.dataSource, grid is "undefined or null" (which is what the error is telling you).
You should be using an id selector:
var grid = $("#kADUser").data("kendoGrid");
In general, I'd suggest to avoid compound statements and keep it at one statement per line. This will make debugging much easier.

Categories

Resources