Table with combobox on one of fild data-binding - c#

I need create table with field with combobox on page. But I can't bind valid items to combobox, all combobox have default values - 'Please Select...'. Can you help me?
My html code fragment:
<td><label data-bind="text: name"></label></td>
<td><label data-bind="text: description"></label></td>`enter code here`
<td>
<select class="controls contol-width span2" id="cmbSelectedInfo" required="required" data-bind="
options: vm.infoes,
value: vm.selectedInfoID,
optionsText:'code',
optionsValue: 'infoID',
optionsCaption: 'Please Select...'"></select>
</td>
My viewmodel in typescript:
class MyViewModel {
infoes: KnockoutObservableArray<any>;
selectedInfoID: KnockoutObservable<number>;
constructor() {
this.infoes = ko.observableArray();
this.selectedInfoID = ko.observable<number>();
}
getInfoes(url: string, onError: (message: string) => {}) {
(<any>this).getJson(url, (data: any) => {
<any>this.infoes((<any>ko).mapping.fromJS(data).infoes());
} ,(message: string) => {
onError(message);
});
}
getJson(url: string, onSuccessed: (data: any) => {}, onError: (message: string) => {}) {
var self = this;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: (data) => {
if (data.succeeded) {
onSuccessed(data);
} else {
onError((<any>data).error);
}
},
error: (data) => {
onError((<any>data).error);
}
});
}

Related

Delete all checked element in list

I display a list of element from a list, and I have to display a checkbox in front of each element, and then delete all checked element, I wrote a jquery code for do this but it removes just the first element checked, how I should do to remove all checked items
<button type="submit" class="btn fsc-btn-3" id="AllDelete">
<i class=" fa fa-check"></i>
<span>#Labels.Global_DeleteSelection</span>
</button>
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" id="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label>
</td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
jQuery code:
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery("#checkFile").val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);
Controller :
[HttpPost]
public ActionResult DeleteMultiCredit(int FileId)
{
DeleteCreditModel model = new DeleteCreditModel();
model.Delete(FileId);
return RedirectToAction("Index");
}
Try this : first of all you cannot use same id for all checkbox, so either generate unique ids for each one or remove id attribute
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label></td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
now use $(this).val() to get value of each checkbox instead of using id of checkbox to read value
jQuery(function () {
jQuery('#AllDelete').click("click", function () {
//you can use :checked directly in selector, so if condition not required
jQuery('input[type="checkbox"]:checked').each(function() {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },//read your value here
success: function (data) {
}
});
});
});
})(jQuery);
Use jQuery(this) instead of jQuery("#checkFile")
Just like this :
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);
try below code
jQuery(function () {
jQuery('#AllDelete').click(function () {
jQuery('input[type="checkbox"]').each(function() {
if(this.checked){
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);

How to sort partial view telerik grid?

I' using telerik grid with mvc C#.
I create the telerik grid inside the partial view.My telerik grid sortiong is not working.
This is my Controller
public ActionResult Index()
{
var query = from c in db.tblCompanies
select c;
return View(query.ToList());
}
public ActionResult SearchCompany(string CompanyName)
{
var query = from c in db.tblCompanies
select c;
if (CompanyName != "")
{
query = query.Where(s => s.CompanyName.Contains(CompanyName));
}
return PartialView("_comList", query);
}
This is my view
script type="text/javascript">
function SearchCompany() {
var CompanyName = document.getElementById('txtCompanyName').value;
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("SearchCompany", "Company")',
data: ({ CompanyName: CompanyName }),
success: function (data) {
//alert(data);
$('#CompList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
<table>
<tr>
<td>Company Name:</td>
<td>#Html.TextBox("txtCompanyName")</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Search" onclick="SearchCompany();" /></td>
</tr>
</table>
<div id="CompList">
#Html.Partial("_comList", CompanyList)
</div>
this is my partial view
#(Html.Telerik().Grid(Model)
.Name("CompanyGrid")
.Columns(columns =>
{
columns.Bound(o => o.CompanyId).Width(5).Title("ID"); ;
columns.Bound(o => o.CompanyName).Width(50);
columns.Bound(o => o.CompanyAddress).Width(60).Title("Address");
columns.Bound(o => o.Phone).Width(20);
columns.Bound(x => x.PKComID)
.Width(30)
.Template(x => Html.ActionLink("Edit", "Edit", new { id = x.PKComID }))
.ClientTemplate(" EDIT ")
.Title("Edit").Sortable(false);
columns.Bound(x => x.PKComID)
.Width(30)
.Template(x => Html.ActionLink("Delete", "Delete", new { id = x.PKComID }, new { onclick = "return confirm('Are you sure you wish to delete this Company?');" }))
.ClientTemplate(" EDIT ")
.Title("Delete").Sortable(false);
})
.Pageable(paging => paging.PageSize(15).Style(GridPagerStyles.NextPreviousAndNumeric).Position(GridPagerPosition.Bottom))
.Sortable()
)
what is the wrong with my code.. sorting is not working
please help me.
Make sure that you have correctly implemented all steps from the Telerik ASP.NET MVC - Grid - Sorting demo.

Pass ID in Html.ActionLink via ajax to get partial view

I have an MVC View page, strongly-typed to an enumerated product list. Each list item has an Html.ActionLink with a unique id. In my jquery file, I have an $.ajax function which should process the link with the corresponding id . The intent is to load a partial view on the same page, with that item's information, to allow editing for whatever item has been clicked. I don't want the actionr to result in a separate page, or generate a post to the server.
// here is the MVC stuff
#model IEnumerable<SimpleAjax.Models.Product>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { id = "btnShowEdit" + item.Id, #class= ".button_action"})
|
</td>
</tr>
}
<div id="showEditProd">
</div>
//inside controller
public ActionResult ShowEdit(int id)
{
Product prod = db.Product.Find(id);
ProductViewModel viewModel = new ProductViewModel
{
EditProduct = prod
};
return PartialView(viewModel);
}
//inside a separate partial view page
#model SimpleAjax.Models.ProductViewModel
#using (Html.BeginForm("Index_AddItem", "Home", FormMethod.Post, new { id = "fid" }))
{
<div>
#Html.LabelFor(model => model.EditProduct.Name)
#Html.EditorFor(model => model.EditProduct.Name)
</div>
<div>
#Html.LabelFor(model => model.EditProduct.Price)
#Html.EditorFor(model => model.EditProduct.Price)
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
now below works as expected, when I have hardcoded IDs:
$('#btnShowEdit1,#btnShowEdit2,#btnShowEdit3').click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
The above jquery works as desired. The partial view gets loaded on the same page as enumerated list. But obviously I don't want to hardcode variables. I may have x number of #btnShowEdit. I want to utilize a class, correct? So I have ".button_action" class that will enumerate the Id. But when I do that, as below, the link navigates to a separate page.
these go to a separate page, not what I want
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
//also tried this...
$('.button_action').each(function (index) {
$('#btnShowEdit' + index).click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
I know there's gotta be a simple solution.Thanks for your help in advance.
Any specific reason for not using the Ajax HTML-helper?
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink(v=vs.108).aspx
You can use it as an actionlink, but it is done async and the result can be placed in your showEditProd.
#Ajax.ActionLink("Action",
"Controller",
_YOURID_,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "showEditProd",
OnComplete = "your_js_function();" })
In case anyone else needs the solution to the above... It was too simple to believe.The jquery ajax code does not need an id htmlattribute from the Html.ActionLink. In fact, this extra attribute is what was causing the trouble. The jquery ajax recognizes the id from the "this.href' as that is the route controller along with the id parameter. Therefore I removed the id from htmlattributes in the actionlink. Now it's working as expected.
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { #class= ".button_action"})
in js file
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
Check this:
$('.button_action').click(function (e) {
e.preventDefault() // this prevent default behavior for hyperlink on 'click' event

MVC Dynamic content onchange of dropdownlist

I have a question on how to achieve the following:
I have a dropdownlist with activities and I want on the onchange event of an activity, that my list would be fetched with the id that is set in my model with ajax
example of my code is as following
Ajax Method to set The ID
function GetSelectedValue(DropDownID, HiddenFieldID) {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$('#' + DropDownID).change(function () {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$.ajax({
url: 'Afmeldingen',
type: "POST",
data: JSON.stringify({ 'ActiviteitenID': $('#' + DropDownID + ' option:selected').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
jQuery.globalEval(data.Callback);
},
error: function (error) {
//alert(error);
}
});
});
}
$(document).bind('pageinit', function () {
GetSelectedValue('details', 'act_id');
});
The Form element
#using (Html.BeginForm())
{
<div data-role="collapsible" data-inline="true" data-content-theme="b" data-collapsed="false">
<h3>#DateTime.Today.ToShortDateString()</h3>
<div data-role="collapsible-set" data-inline="true" data-content-theme="b" data-collapsed="true">
<select id="details">
#foreach (var item in Models.Taken.ActivityList)
{
<option value="#item.ID">#item.Comments</option>
}
</select>
#Html.Hidden("act_id")
#foreach (var item in Talent.Subscription.Fetch(null, Models.Taken.ActID ?? 1L, null, null))
{
<div data-role="collapsible" data-content-theme="b" data-collapsed="true">
<h3>
#Html.Label("", item.Participant.CompleteName)
</h3>
#Html.CheckBoxFor(m => m.DeelnemerActive.HasValue, htmlAttributes: new { data_role = "CheckBox" })
#foreach (var af in Talent.Afmelding.Fetch(null, Models.Tasks.ActID ?? 1L, null, null))
{
#Html.Label("", "Comments")
#Html.TextBox("Reason", af.Reason);
}
</div>
}
</div>
</div>
}
I hope you can help me to achieve this, or that you have an idea how to do this
This is probably the best example I can find that would help you.
http://blog.krisvandermast.com/CommentView,guid,b1a264ac-c48f-463e-9f55-db24e2a9b635.aspx
He loads data from a partial view dynamically on the onclick of a
button. You could use your onchange here.
-
Have a look at this example to see how cascading dropdowns work:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/cascading-dropdownlist-in-Asp-Net-mvc/
-
You could also consider using knockout js, like described here:
http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html

Jquery Post not reaching MVC Controller

Apologies if this i trivial, i have read many other comments and still cannot see what is wrong. I have done a few tutorials and they seem to work ok, so I am really missing something simple.
I have a basic 'remove' link that i want to do a JQuery Post back to the controller to remove an item from the database and then update the view.
My View / Javascript:
<script type="text/javascript">
$(function () {
$(".RemoveLink").click(function () {
var id = $(this).attr("data-id");
if (id != '') {
$.post("#Url.Content("~/Agent/Remove")", { "id": id }, function (data) { alert('Here i am'); });
}
});
});
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.ID" >Remove</a>
</td>
</tr>
}
My Controller:
[HttpPost]
public ActionResult Remove(int id)
{
return Json(new { Data = "true" });
}
Any assistance will be great.
Use #Url.Action("Remove", "Agent") instead.
#Url.Content("...") is used to locate any static content of the site.
Cheers
Below code works well.
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<input type="button" class="RemoveLink" id="#item.ID" Value="Remove" />
</td>
</tr>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.RemoveLink').live("click", function () {
Remove($(this));
});
});
function Remove(_this) {
var Id= $(_this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("Remove", "Agent")',
data: "{id: '" + Id + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
//do something here......
},
error: function () {
}
});
}
</script>

Categories