I am using Ajax to populate a partial view in my web application. This partial view contains a link to download a PDF file based upon the data that is currently in the table / List<> of the model.
The partial view is as follows:
#model Inspection_Reports.ViewModel.SummaryReportViewModel
<table id="summaryReportTable" class="table-condensed table-striped">
<thead><tr><td>Inspector</td><td>Attendant</td><td>Property</td><td>Room Number</td><td>Date</td><td>HK Score</td><td>Maint. Score</td></tr></thead>
<tbody id="resultsContainer">
#foreach (var report in #Model.reportsList)
{
<tr><td>#report.inspect.empName</td><td>#report.attendant.empName</td><td>#report.location.locName</td><td>#report.room</td><td>#report.endTime</td><td>#report.hkDisplay</td><td>#report.mainDisplay <input type='hidden' name='reportId[i]' /></td></tr>
}
</tbody>
</table>
#Html.ActionLink("Export as PDF", "GenerateSummaryPDF", new { summary = #Model.reportsList })
GenerateSummaryPDF method:
public FileResult GenerateSummaryPDF(List<report_summary> summary) {
Document doc = pdfWorker.readyDocument("Inspection Report, Generated " + DateTime.Now.ToString("MM-dd-yyyy"));
pdfWorker.createSummaryReport(doc, summary);
pdfWorker.savePDF(doc, String.Format("{0}/Inspection_Summary_{1}.pdf", #"C:\Users\Khandokar\Desktop", DateTime.Now.ToString("MM-dd-yyyy")));
return File(String.Format("{0}/Inspection_Summary_{1}.pdf", #"PATH", DateTime.Now.ToString("MM-dd-yyyy")), "application/pdf", "Inspection.pdf");
The problem is that, when the GenerateSummaryPDF is called, the summary list is empty. The list is not null, but merely has no items in it.
However, I am not sure why this is the case. When I click the export link, there is data in Model.reportsList; it is visible in the table and further verified by setting a breakpoint.
The parent view:
#model Inspection_Reports.ViewModel.SummaryReportViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Report Summaries</title>
</head>
<body>
<h2>Summary Reports</h2>
<form class="form-horizontal">
<div class="form-group"><label class="control-label col-md-2">Start Date: </label><div class="col-md-4"><input class="form-control summaryFilter" type='text' value="#Model.fromDate" name='startDate' id='startDate' /></div><label class="control-label col-md-2">End Date: </label><div class="col-md-4"><input type='text' value="#Model.toDate" class='form-control summaryFilter' name='endDate' id='endDate' /></div></div>
<div class="form-group">
<label class="control-label col-md-2">Filter By: </label>
<div class="col-md-4">
<select class="form-control summaryFilter" name="filterTypeList" id="filterTypeList">
<option value="">Select...</option>
<option value="Property">Property</option>
<option value="Attendant">Attendant</option>
<option value="Inspector">Inspector</option>
</select>
</div>
<label class="control-label col-md-2">Filter Selection: </label><div class="col-md-4">
<select class="form-control summaryFilter" name="filterSelectionList" id="filterSelectionList"></select>
</div>
</div>
</form>
<div id="reportResults">
#{Html.RenderPartial("SummaryPartialView", Model);}
</div>
#section scripts {
<script src="~/Scripts/ajaxReports.js"></script>
}
</body>
</html>
The methods used to populate the partial view (based largely on this article: https://cmatskas.com/update-an-mvc-partial-view-with-ajax/)
[HttpGet]
public async Task<ActionResult> GetSummaryReports(string fromDate, string toDate, string filterType, string filterValue)
{
DateTime from = Convert.ToDateTime(fromDate);
DateTime to = Convert.ToDateTime(toDate);
Int32 filterValID = Int32.Parse(filterValue);
SummaryReportViewModel vm = await GetSummaryVM(from, to, filterType, filterValID);
return PartialView("SummaryPartialView", vm);
}
private async Task<SummaryReportViewModel> GetSummaryVM(DateTime from, DateTime to, string filterType, int filterValID)
{
SummaryReportViewModel vm = new SummaryReportViewModel();
to = to.AddDays(1);
var reports = dbContext.report_summary.Where(r => r.endTime <= to && r.endTime >= from);
if (filterType.Equals("Property"))
{
reports = reports.Where(r => r.locationID == filterValID);
}
else if (filterType.Equals("Attendant"))
{
reports = reports.Where(r => r.employee == filterValID);
}
else
{
reports = reports.Where(r => r.inspector == filterValID);
}
vm.reportsList = reports.ToList<report_summary>();
return vm;
}
The Ajax
$(".summaryFilter").change(function () {
var fromDate = $("#startDate").val();
var toDate = $("#endDate").val();
var filterType = $("#filterTypeList").val();
var filterValue = $("#filterSelectionList").val();
if (filterValue != null || typeof (filterValue) != typeof (undefined)) {
$.ajax({
url: "GetSummaryReports?fromDate=" + fromDate + "&toDate=" + toDate + "&filterType=" + filterType + "&filterValue=" + filterValue,
type: 'get',
success: function (data) {
$("#reportResults").html(data);
},
});
}
});
Thanks for any help.
You're asking a bit much of a Get method - you should instead switch to a form that Posts to allow model binding to handle your complex list object.
Related
I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers
Tool Model
public class Tool
{
public int Id { get; set; }
public string ToolId { get; set; }
public string Adapter { get; set; }
public string Description { get; set; }
public string TNumber { get; set; }
public List<string> ComponentList { get; set; }
public List<string> AccessoryList { get; set; }
public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
public List<string> toolList = new List<string>();
}
Partial View Controller
public ActionResult PartialView()
{
Tool newTool = new Tool();
List<string> tools = new List<string>();
tools = backgroundLoad();
newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
foreach (string tool in tools)
{
newTool.ToolIdDescription = GetToolDescription(tool);
}
return View(newTool);
}
Controller to recieve Datasets
public ActionResult GetDataSet(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description =
Description.InnerText;
var Adapter =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return View(selectedTool);
}
else return View();
}
View which contains the list
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
#Html.Partial("GetDataSet", new MiniWeb.Models.Tool())
View which displays the tool information
#model MiniWeb.Models.Tool
#{
ViewBag.Title = "GetDataSet";
}
#{
ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>Tool Selection </h2>
<div class="Tool">
<span id ="id">
#Html.LabelFor(m => Model.ToolId)
#Html.TextBoxFor(modelItem => Model.ToolId)
</span>
<br/>
<span id="Description">
#Html.LabelFor(m => Model.Description)
#Html.TextBoxFor(modelItem => Model.Description)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m=> Model.Adapter)
#Html.TextBoxFor(modelItem => Model.Adapter)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m => Model.TNumber)
#Html.TextBoxFor(modelItem => Model.TNumber)
</span>
<span>
<button> Save </button>
</span>
</div>
Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.
With some more research I was able to figure out how to solve my problem. Turns out all I needed was some AJAX. I used an Ajax.Actionlink instead of an HTML action link and was able to load up my partial view in a div on the page. Here is my new view and controller. The partial view stayed the same.
View
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Ajax.ActionLink(item.Key, "_Partially", new { id = item.Key },new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "ToolInfo",
InsertionMode = InsertionMode.Replace,
})
</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
<div id="ToolInfo">
</div>
and my new controller which is returns a PartialView looks like this
Partial View Controller
public PartialViewResult _Partially(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream, Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description = Description.InnerText;
var Adapter = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return PartialView("_Partially", selectedTool);
}
return PartialView();
}
Hopefully this answer will help others like me in the future. Thanks for reading.
You're going to want to create a form on your partial view that will submit the data to the main pages controller.
You can find more information in this article.
I am building an MVC based ASP.NET application. One of the functionalities should be to be able to upload files asynchronously using a progress bar.
I've had success with uploading files without the progress bar. The code below does that.
View Code:
<input class="file" type="file" name="file" id="file" />
<input type="submit" name="submit" value="Upload" />
Controller Code:
public ActionResult Upload(){
return View();
}
[HttpPost]
public ActionResult Upload(Resource resource)
{
try
{
if (resource.File.ContentLength > 0)
{
var fileName = Path.GetFileName(resource.File.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Resources"), fileName);
resource.File.SaveAs(path);
}
}
catch (Exception e)
{
Console.WriteLine("Cannot upload file. Exception of type : {0}", e.ToString());
}
return RedirectToAction("Upload");
}
This code works absolutely fine. With slight modifications, I am even able to upload multiple files. But, even though I've tried finding it, I am not able to upload files using a progress bar.
Any help is appreciated.
This is how I do it - the controller code is much the same, but the client has some javascript in it to monitor and update progress of the ajax posting. The UI Html is like this:
<div id="uploadDetails" class="form-group">
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" name="file" id="file" />
</span>
</span>
<input type="text" id="filename" class="form-control fullwidth" readonly />
<span class="input-group-btn">
<button class="btn btn-primary" type="button" id="uploadFile"><span class="glyphicon glyphicon-upload"></span> Upload File </button>
</span>
</div>
</div>
And the javascript for the upload like this:
$(document).on('click', '#uploadFile', function (e) {
var fileElement = document.getElementById('file');
var file = fileElement.files[0];
var formData = new FormData();
formData.append("filename", fileElement.files[0].name);
formData.append("id", '#Model.SharedIP.Id');
formData.append("file", file, fileElement.files[0].name);
var html = $('#uploadFile').html();
$('#uploadFile').html('Uploading...');
$.ajax({
url: "#Url.Action("UploadFile", "SharedIP")",
type: "POST",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
$('#uploadFile').html('Uploading... ' + Math.round((evt.loaded / evt.total) * 100) + '%');
}
else $('#uploadFile').html('hmmm');
}, false);
return xhr;
},
success: function (results) {
updateFilesList();
$('#uploadFile').html(html);
fileElement.files = [];
var control = $('#file');
control.replaceWith(control.clone(false));
$('#filename').val("")
},
error: function (xhr, ajaxOptions, thrownError) {
$('#uploadFile').html(html);
alert(xhr.responseText);
}
});
});
For completeness, here's the Controller signature, it's .net Core RC1 so might not work in your target framework, but you will get the idea.
[HttpPost]
public IActionResult UploadFile(string filename, Guid id, IFormFile file)
{
IPFile ipfile = new IPFile()
{
ContentType = file.ContentType,
DateUploaded = DateTime.Now,
Filename = filename,
SharedIPId = (id == Guid.Empty ? (Guid?)null : id),
Id = Guid.NewGuid(),
UploadedBy = User.Alias(),
};
ipfile = FileManager.AddFileFromStream(User.Alias(), ipfile, file.OpenReadStream());
return Ok(ipfile);
}
Hope that answers your question.
[EDIT] Just realised this isn't a "progress bar" - but it's got all the workings and % display - to put a progress bar in, you'd just apply CSS to an element that renders the % graphically for you - see posts like http://www.w3schools.com/bootstrap/bootstrap_progressbars.asp for examples.
Here is the code that I have tried. It's a bare minimum code but works as expected. It still has some bugs and I would appreciate if someone could make it bug free.
Some bugs:
Progress bar does not reset on a new file upload.
Add a button to do the upload (I can do it myself as well).
Model Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NewDeploymentsTesting.Models
{
public class UploadFilesResult
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
}
Controller Code:
using NewDeploymentsTesting.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NewDeploymentsTesting.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadFilesResult>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0) continue;
string savedFileName = Path.Combine(Server.MapPath("~/Content/Resource"), Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new UploadFilesResult()
{
Name = hpf.FileName,
Length = hpf.ContentLength,
Type = hpf.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
}
}
View Code:
#{Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Uploading Files</title>
<link href="~/Content/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap/bootstrap-theme.css" rel="stylesheet" />
<link href="~/Content/jquery.fileupload.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.ui.widget.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.fileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Home/UploadFiles',
autoUpload: true,
done: function (e, data) {
$('.file_name').html(data.result.name);
$('.file_type').html(data.result.type);
$('.file_size').html(data.result.size);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
</script>
</head>
<body>
<div class="container">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add Files ...</span>
<input id="fileupload" type="file" name="files[]" multiple />
</span><br />
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only">0% Complete</span>
</div>
</div><br />
<div class="file_name"></div><br />
<div class="file_type"></div><br />
<div class="file_size"></div><br />
</div>
</body>
</html>
Here is what it looks like on the browser window.
I have successfully written a MVC4 webapi that takes CompanyID, name and posts it to DB. I need to change it in such a way that the user can enter multiple values for CompanyID with their Names and Save it to DB in one shot. How can I do that? Here's my code
--Index.cshtml
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome Web API!</h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<p>
For API documentation: #Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
</p>
<p>
Update/Insert Company info: Click Here!
</p>
</section>
</div>
--Companies.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
var overrides = Array();
function parseform(button) {
var CompanyID = $("#CompanyID").val();
var CompanyName = $("#CompanyName").val();
var lst = {
CompanyID: CompanyID,
CompanyName: CompanyName
}
if (button.attr('value') === "POST") {
console.log("posting : " + lst.toString());
postdata(lst);
} else {
console.log("ERROR");
}
}
function postdata(lst) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/Company/",
data: lst,
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
console.log(status);
$("#response").text(status)
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
var json = jQuery.parseJSON(xhr.responseText);
console.log(json);
$("#response").text(status)
alert(json.Message);
}
});
}
$(document).ready(function () {
$('input:button').click(function () {
parseform($(this));
});
});
</script>
<div id="form">
<label for="CompanyID">CompanyID:</label><input type="text" id="CompanyID" /><br />
<label for="CompanyName">CompanyName:</label><input type="text" id="CompanyName" /><br />
<input type="button" id="Post" value="POST"/>
</div>
<div id="response">
</div>
</body>
</html
In CompaniesController, I have written a call to stored procedure for the POST method to save one record at a time.
How can I Post many rows at a time & what changes should I do to html file.
Thanks
R
How did you declared your variables in your Model. For operating multivalued types, try something like this:
private ICollection<string> _variable;
public ICollection<string> VariableName
{
get
{
if (_variable == null)
{
return new Collection<string> {""};
}
else
{
return _variable;
}
}
set { _variable = value; }
}
i am using knockout to display items on page. I have a list of groups ex: Group 1, Group 2,... each group is in it's own div. When i click on one of the groups it will open and display the items in the group. Some of my groups don't have any items to display and instead of it not showing anything i would like to change that to display: "No items in group"
I am having trouble doing this in the view in javascript and thought i would be able to do it in my knockout/jquery script
View:
<div class="accordion-group elements-by-item">
<div class="accordion-heading">
<a class="ui_title accordion-toggle text_x-large item_accordion_toggle" data-toggle="collapse" data-parent="#ByTimeIndex"
data-bind="text: Title() != null ? Title() : Identity(), attr: { 'href': '#itemContent_' + Id(), 'data-item-id': Id() }">
</a>
</div>
<div class="accordion-body collapse state-loading" data-bind="attr: { 'id': 'itemContent_' + Id(), 'data-item-id': Id() }">
#Html.Partial("_itemElements")
</div>
</div>
**_itemElements Page:**
<div class="accordion-inner no_border" data-bind="foreach: Children">
<div class="element">
........
</div>
<div>
knockout/Jquery js
$idx.ItemsRetrieved = new Array();
$idx.GetItemContent = function (element) {
var _itemId = element.attr('data-item-id');
var _elementData = $idx.itemData;
this.GetElementContent({
groupId: _itemId,
groupData: _elementData.items,
elementData: _elementData,
apiUrl: _courseIndexOptions.GetitemUrlPrefix + _itemId,
accordionBodySelector: '.accordion-body[data-item-id="' + _itemId + '"]',
accordionBtnSelector: 'a[data-item-id="' + _itemId + '"]',
viewModel: $idx.TimeViewModel
});
}
$idx.GetElementContent = function (options) {
if (linq.From($idx.ItemsRetrieved).Any(function (x) { return x == options.groupId })) {
$(options.accordionBodySelector).removeClass(constants.StateClasses.Loading);
return;
}
return Ajax.Get({
Url: options.apiUrl,
OnSuccess: function (data) {
var _items = linq.From(options.groupData);
var _itemToUpdate = _items.Where(function (x) { return x.Id == options.groupId; });
if (_itemToUpdate.Any()) {
_itemToUpdate.First().Children = data.Items;
}
ko.mapping.fromJS(options.elementData, options.viewModel);
sections.ElementArray.AddRange(data.Items);
$(options.accordionBodySelector).removeClass(constants.StateClasses.Loading);
$idx.ItemsRetrieved.push(options.groupId);
$(options.accordionBtnSelector).click();
}
});
how can i check if the children ItemsRetrieved = 0 and to set a message "No Items" to show in the view page?
You can do that :
<div class="accordion-inner no_border" >
<div data-bind="foreach: Children">
<div class="element">
</div>
</div>
<span data-bind="if : Children().length == 0">No items in group</span>
<div>
I hope it helps.
I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
In a view, I have 2 DropDownList and TextArea and 2 buttons :
DropDownList Poste
DropDownList Fonction
Button Ajouter
Button Enregistrer
TextArea
The Values of the TextArea are added from the DropDownList 'Fonction' when I click on the button 'Ajouter'.
I want to retrieve those values in a local variable. And that when the user click on the button 'Enregistrer'(submit).
This is the code of the view :
<% using (Html.BeginForm("Store", "Fonction")) { %>
<h2>Gérer les droits</h2>
<form id="form1" runat="server">
<fieldset><legend>Gestion</legend>
<div>
<%:Html.Label("Poste :")%><%: Html.DropDownListFor(model => model.SelectedPoste, Model.PostesItems)%>
</div>
<br />
<div>
<%:Html.Label("Fonction :")%><%: Html.DropDownListFor(model => model.SelectedFonction, Model.FoncItems, new { #id = "ff" })%>
</div>
<br />
<div><input type="button" value="Ajouter" id="aj" onclick="addtext()"/></div>
<br />
<div>
<textarea id="tt" cols="10" name="S1" rows="8" readonly="true"></textarea>
</div>
</fieldset>
<br />
<div><input type="submit" value="Enregistrer" id="sv" /></div>
</form>
<script language="javascript" type="text/javascript">
var storedValues = [];
function addtext() {
var ff = document.getElementById('ff');
var tt = document.getElementById('tt');
var selectedValue = ff.options[ff.selectedIndex].value + " ";
if (storedValues.indexOf(selectedValue) === -1) {
storedValues.push(selectedValue)
tt.value = storedValues.join('')
}
}
</script>
and this is the code of the methode store (for the submit) in the controller :
[HttpPost]
public ActionResult Store(FlowViewModel model)
{
if (ModelState.IsValid)
{
Fonction_Poste FP = new Fonction_Poste();
FP.ID_Poste = model.SelectedPoste;
FP.ID_Fonction = model.SelectedFonction;
FP.Droit = 1;
System.Web.UI.HtmlControls.HtmlTextArea htaDemo = (System.Web.UI.HtmlControls.HtmlTextArea)(form1.FindControl("tt"));
String Value = htaDemo.Value;
db.Fonction_Postes.Add(FP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
So as you see, Itried to do retrive values using this statement but that's didn't give any result :
System.Web.UI.HtmlControls.HtmlTextArea htaDemo = (System.Web.UI.HtmlControls.HtmlTextArea)(form1.FindControl("tt"));
String Value = htaDemo.Value;
If you have any property in the FlowViewModel for the value of the text area to bind to, you can use it.
If you have any property with the name S1, the value of the text area will be automatically bound.
Because, in ASP.Net MVC, there are no server side controls that you can refer to. Everything is model bound automatically.
Else, you can either create a property or use the FormCollection to get the value and use it accordingly.
Please share your implementation related to this to guide better.