script
<script type="text/javascript">
$(document).ready(function () {
$('musteri_sno').change(function () {
$('form_sayac_secimi').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
}
});
}
return false;
});
});
});
</script>
html
#using (Html.BeginForm("SayacSecimiPartial", "SayacOkumalari", FormMethod.Post, new { id = "form_sayac_secimi" }))
{
<table>
<tr>
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
<td>
<input type="submit" value="Uygula" />
#Html.Hidden("sno", new { sno = ViewData["sno"] })
</td>
</tr>
</table>
}
I want to fill second dropdown with values that is returned from first one.How can I do this?
Thanks.
In the success callback of your ajax call, build the option tag filled with the values you are returned and then append it to the select tag named "sayac_no".
success: function(result) {
var opt = '';
for (var i = 0; i < result; i++) {
opt += '<option value="' + result[i].value + '">' + result[i].name + '</option>';
}
$('select[name=sayac_no]').html(opt);
}
I suppose the result object is a list of objects with two properties, name and value.
Modify it accordingly to your needs and improve it because this is just a very basic version.
Related
I am always getting null value through checkbox in mvc. If the checkbox is checked or uncheck it contain null value only.
Here is my code,
View Page
#model IEnumerable<SchoolWebApplication.Models.EventMaster>
<table id="tblEvent" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px; display:none">Event Id</th>
<th style="width:150px">Event</th>
<th style="width:150px">Active</th>
</tr>
#if(Model != null)
{
foreach (SchoolWebApplication.Models.EventMaster eventMaster in Model)
{
<tr>
<td class="EventID" style="display:none">
<span>#eventMaster.EventID</span>
</td>
<td class="Event">
<span style="color:darkgreen">#eventMaster.Event</span>
<input type="text" value="#eventMaster.Event" style="display:none; color:darkgreen" />
</td>
<td class="IsActive">
<span style="color:darkgreen">#eventMaster.IsActive</span>
#if (#eventMaster.IsActive == true)
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" checked="checked" name="abc"/>
}
else
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" name="abc"/>
}
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</td>
</tr>
}
}
</table>
<script type="text/javascript">
function AppendRow(row, EventID, Event, IsActive) {
//Bind EventID.
$(".EventID", row).find("span").html(EventID);
//Bind Event.
$(".Event", row).find("span").html(Event);
$(".Event", row).find("input").val(Event);
//Bind IsActive.
$(".IsActive", row).find("span").html(IsActive);
$(".IsActive", row).find("input").val(IsActive);
$("#tblEvent").append(row);
};
//Edit event handler.
$("body").on("click", "#tblEvent .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblEvent .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
$(this).hide();
var event = {};
event.EventID = row.find(".EventID").find("span").html();
event.Event = row.find(".Event").find("span").html();
event.IsActive = row.find(".IsActive").find("span").html();
$.ajax({
type: "POST",
url: "/Event/Update",
data: JSON.stringify({ eventMaster: event }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.IsActive);
}
});
});
</script>
Controller
try
{
EventMaster updatedEvent = (from c in entities.eventMaster
where c.EventID == eventMaster.EventID
select c).FirstOrDefault();
updatedEvent.Event = eventMaster.Event;
updatedEvent.IsActive = eventMaster.IsActive;
entities.SaveChanges();
return new EmptyResult();
}
catch (Exception ex)
{
return View();
}
Now, in table there is a three field EventID, Event and Active. In active there is a checkbox containing at update time.
Now, the issue is coming that if the checkbox is check or not check it is containing null value only.
So thats why at the fetch time it showing uncheck only.
Thank You.
Asking for the .val of a checkbox will get you the contents (if any) of the value attribute on the input element - this will not change when the user checks the box.
To check if a checkbox is checked in jQuery you should use something like:
if (input.is(":checked")){}
At the moment, you're storing the current value of .IsActive in the span and the value of the checkbox, and then when the update method runs, just grabbing that same value and putting it into the span - resulting in not updating anything.
Looking further at your code though - you should confirm what your method is actually posting back to the server - looking at it you are passing raw HTML into some parameters on the object:
event.IsActive = row.find(".IsActive").find("span").html();
At best, event.IsActive will be the string "True" (or False), rather than an actual boolean that your model is expecting. You would be better off changing that line to something like:
event.IsActive = row.find(".IsActive").find("input").is(":checked");
And then confirm what is being sent to the server in the network tab of your browser.
I have followed a tutorial that I found at http://www.dotnetcurry.com/aspnet-mvc/933/knockoutjs-aspnet-mvc-tutorial-beginner. The tutorial is great and covers add and update however there are no click handlers included for delete or cancelling the update.
I tried to follow the same pattern the author provided for saving data and I created a function to delete, however this does not work.
function deleteData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id > 0) {
postUrl = "/concerns/delete"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Deleting");
})
};
This is the table:
<table class="table">
<tr>
<th>concerns_id</th>
<th>concerns_description</th>
<th></th>
</tr>
<tbody data-bind="foreach: ConcernCollection">
<tr data-bind="template: { name: Mode, data: $data }"></tr>
</tbody>
</table>
The Templates:
<script type="text/html" id="display">
<td data-bind="text: concerns_id"></td>
<td data-bind="text: concerns_description"></td>
<td>
<button class="btn btn-success kout-edit">Edit</button>
<button class="btn btn-danger kout-delete">Delete</button>
</td>
</script>
<script type="text/html" id="edit">
<td><input type="text" data-bind="value: concerns_id " /></td>
<td><input type="text" data-bind="value: concerns_description" /></td>
<td>
<button class="btn btn-success kout-update">Update</button>
<button class="btn btn-danger kout-cancel">Cancel</button>
</td>
</script>
Full JS without the Delete Function that I tied to add:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/concerns/GetConcerns",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
concerns_id: ko.observable(element.concerns_id),
concerns_description: ko.observable(element.concerns_description),
Mode: ko.observable("display")
};
viewModel.ConcernCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
saveData(current);
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = {
concerns_id: ko.observable(0),
concerns_description: ko.observable(),
Mode: ko.observable("edit")
}
viewModel.ConcernCollection.push(current);
});
function saveData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id && currentData.concerns_id() > 0) {
postUrl = "/concerns/Edit"
}
else {
postUrl = "/concerns/Create"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Saving");
})
}
});
Any help or guidance would be apprenticed this is my first time working with Knockout.js
Thanks,
I'm not gonna lie, your code is a little hard to follow. I really don't think you're getting the full knockout experience. I put together a tiny little demo to show you just how you can use knockout to add/remove items from a list and display them.
Knockout should be used for data-binding. You should honestly never need to use jQuery to attach listeners by class. That is how your code becomes spaghetti.
While your question doesn't ask it, I strongly recommend visiting http://learn.knockoutjs.com/ before continuing your tutorial much further.
I hope this helps!
function ViewModel() {
var self = this;
self.Items = ko.observableArray();
self.DeleteRow = function(row) {
// Your ajax call here
self.Items.remove(row);
}
self.AddRow = function() {
self.Items.push("Added Item at " + new Date());
}
self.LoadFakeData = function() {
// Put ajax calls here
for (i = 0; i < 10; i++) {
self.Items.push("Item " + i);
}
}
self.Load = function() {
self.LoadFakeData();
}
self.Load();
}
ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: Items">
<span data-bind="text: $data"></span>
<span data-bind="click: $parent.DeleteRow">X</span>
<br>
</div>
<hr>
<span data-bind="click: AddRow">Add Row</span>
I am trying to get the viewmodel on the page to update when a partial view is updated via an ajax post. The partial view updates correctly but on the next update call the model seesm to have reverted back to the orginal state.
The partial view is a table and I am either adding or deleting a row. The codde is included below any ideas as to how this can be done.
page code is
<div class="filters">
<fieldset class="source">
<legend>Search Attributes</legend>
<div id="attributes-filter">
#Html.Partial("_EditSearchQuery")
</div>
</fieldset>
</div>
<div>
<a id="addRowLink" class="add-row-link" href="#">Add new clause</a>
</div>
</div>
</div>
-- partial view is
<table id="searchClauses" class="clauses">
<tbody>
<tr class="header">
<td class="add-remove"></td>
<td class="logical">And/Or</td>
<td class="field">Field</td>
<td class="operator">Operator</td>
<td class="value">Value</td>
</tr>
#foreach (SearchClause item in Model.searchClauses)
{
<tr class="clause clause-row" id=#item.RowID>
<td class="add-remove">
<a href="#" title="Remove this filter line" id=#item.ID >Delete</a>
</td>
<td>
#Html.DropDownListFor(modelitem => item.logicalTypeValue, new SelectList(item.logicalTypeList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.DropDownListFor(modelitem => item.fieldListValue, new SelectList(item.fieldList, "Value", "Text", "Selected"))
</td>
<td>
#Html.DropDownListFor(modelitem => item.operatorListValue, new SelectList(item.operatorList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.TextBoxFor(modelitem => item.valuesList[0], new { style = "width: 130px" })
</td>
</tr>
}
</tbody>
-- script
<script type="text/javascript">
$(function () {
// Save quiz view - new or existing.
$("#attributes-filter").on("click", "a", function () { // A jQuery delegated event - #EditQuiz is always present, a.SaveQuiz only exists when the _ElearningQuiz partial view is loaded.
deleteRow($(this).attr("id"));
});
function deleteRow (id) {
var rowData = {
'id': id,
'model' : #Html.Raw(Json.Encode(Model))
};
$.ajax({
url: "/Participant/DeleteClause",
type: "POST",
data: JSON.stringify(rowData),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
};
$("#addRowLink").click(function () {
var model = #Html.Raw(Json.Encode(Model))
$.ajax({
url: "/Participant/AddClause",
type: "POST",
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
});
});
</script>
-- controllers
[HttpPost]
public ActionResult AddClause(DynamicSearchModel model)
{
int campaignId = SessionManager.CampaignId;
int clientId = SessionManager.ClientId;
var newClause = _participantServiceClient.NewSearchClause(campaignId, clientId, 2);
newClause.ID = model.searchClauses.Count + 1;
model.searchClauses.Add(newClause);
return PartialView("_EditSearchQuery", model);
}
[HttpPost]
public ActionResult DeleteClause(string id, DynamicSearchModel model)
{
int _id = int.Parse(id);
model.searchClauses.RemoveAt(_id - 1);
return PartialView("_EditSearchQuery", model);
}
I have some ajax forms in my page and I need to get the form Id or some element inside the form when the OnSuccess function is called, example:
<li>
#using (Ajax.BeginForm(new AjaxOptions
{
OnSuccess = "form.onSuccess"
}))
{
#Html.TextBoxFor(m => m.TaskId)
<button type="submit">Save</button>
}
</li>
how can I get?
Option 1:
#using (Ajax.BeginForm(new AjaxOptions{OnComplete = "DefaultEditOnComplete(xhr, status, 'Person')"}))
{
//Person data and submit button
}
function DefaultEditOnComplete(xhr, status, entityName) {
//xhr - the ajax response
//status - the response text, ex. "success"
//entityName - your custom argument, in this example 'Person'
alert('DefaultEditOnComplete fired for ' + entityName);
}
Option 2:
$('form').submit(function () {
$(this).addClass('activeForm');
});
#using (Ajax.BeginForm(new AjaxOptions{OnSuccess= "JaxSuccess(xhr, status)"}))
{
....
}
function JaxSuccess(xhr, status) {
var active = $(".activeForm");
//Do some stuff here
.....
//When Done, remove the activeForm class, making everything clean
$(".activeForm").removeClass('activeForm');
}
Option 3:
Abandon Ajax.BeginForm, and substitute for regular form and jquery pairing:
#using (Html.BeginForm("SomethingNice", "Home", FormMethod.Post, new { #id = "CoolForm", #class = "ajaxForm" }))
{
#Html.LabelFor(m => m.Rating)
#Html.TextBoxFor(m => m.Rating)
#Html.LabelFor(m => m.Comment)
#Html.TextBoxFor(m => m.Comment)
<input type="submit" value="Submit"/>
}
<script type="text/javascript">
$(function() {
$(".ajaxForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var jaxUrl = form.attr('action');
var dat = form.serialize();
alert(form.attr('id'));
$.ajax({
url: jaxUrl,
data: dat,
success: function(data) {
form.parent().append(data);
},
error: function(xhr, status) {
}
});
});
});
</script>
html
<script type="text/javascript">
$(document).ready(function () {
$("#musteri_sno").change(function () {
var strSayacID = "";
strSayacID = $(this)[0].value; // get the selected state id
var url = "/SayacOkumalari/MusteriSayaclariniGetir/" + strSayacID;
// call controller's action
$.getJSON(url, null, function (data) {
// do something once the data is retrieved
$("#sayac_no").empty();
$.each(data, function (index, optionData) {
$("#sayac_no").append("<option value='"
+ optionData.sno
+ "'>" + optionData.sayac_seri_no
+ "</option>");
});
});
})
.change(); // making sure the event runs on initialization for default value
});
</script>
#using (Ajax.BeginForm("SayacSecimiPartial", "SayacOkumalari", new AjaxOptions { UpdateTargetId = "div_grafik" }, new { id="sayac_secimi_form"}))
{
<table>
<tr>
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
<td>
<input type="submit" value="Uygula" />
</td>
</tr>
</table>
}
This script works on localhost but it does not work on server. There are a lot of script in my project and all of them are working too. Only this script does not work. I cant find, Why?
Thanks.
I suspect the problem line is this one here:
var url = "/SayacOkumalari/MusteriSayaclariniGetir/" + strSayacID;
try changing this to:
var url = '#Url.Action("MusteriSayaclariniGetir", "SayacOkumalari", new {Id = strSayacID })';
As you don't show the controller action, I'm 'assuming' that MusteriSayaclariniGetir has a parameter called Id. If not, then simply change the new {Id = strSayacID }) section to match the parameter name that's required.
var url = "/SayacOkumalari/MusteriSayaclariniGetir/" + strSayacID;
Instead of this try using the following as I have a doubt on the folder structure in your solution.
var url = "../SayacOkumalari/MusteriSayaclariniGetir/" + strSayacID;
Let me know if it doesn't helps, I'll give a try for another thing.