JavaScript in server does not work? - asp.net-mvc

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.

Related

Looking for a cleaner/better way than shown to confirm deletion of a row

I am new to ASP.NET MVC and not that great with Javascript/jQuery.
My end goal is to provide a Delete link to the user to delete a row from a table. I want to do it as a POST operation rather than a GET as this, as I understand, POST is best practice. I wanted to add a confirm dialog before deleting but I didn't want to use the ugly javascript confirm dialog box and I was having problems with the form submitting without waiting for the jQuery dialog box to be answered. So, I turned the submit button into a regular button and added an onclick event which calls a ConfirmDelete javascript method in which I display a custom jQuery confirmation dialog. If answered in the affirmative, I find the form by ID using the keys of the record that the user wants to delete (keys = vendor Id and Effective Date). Once ethe form is found, I use Javascript to submit the form.
-------------------
public static class DateTimeExtensions
{
public static long ToLong(this DateTime value)
{
return long.Parse(value.ToString("yyyyMMddHHmmss"));
}
}
---------------------------------------
#using (Html.BeginForm("Delete", "StateAssessment", new
{
vendorId = Model.VendorId,
effectiveDate = Model.EffectiveDate
},
FormMethod.Post,
new { #id = "Form_" + Model.VendorId + "_" + #Model.EffectiveDate.ToLong() }
))
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.VendorId)
</td>
<td>
#Html.DisplayFor(modelItem => Model.EffectiveDate)
</td>
<td>
#Html.DisplayFor(modelItem => Model.LastTimeStamp)
</td>
<td>
#Html.ActionLink("Edit", "Edit",
new
{
vendorId = Model.VendorId,
effectiveDate = Model.EffectiveDate
})
<input value="Delete" class="btn btn-link" onclick="#string.Format("ConfirmDelete('{0}','{1}')", Model.VendorId, Model.EffectiveDate.ToLong())" />
</td>
</tr>
}
<script type="text/javascript">
function ConfirmDelete(vendorId, effectiveDate) {
var $myDialog = $('<div></div>')
.html('Are you sure that you want to delete this State Assessment?')
.dialog({
modal: true,
autoOpen: false,
title: 'Delete Confirmation',
buttons: {
"OK": function () {
$(this).dialog("close");
var form = $("#Form_" + vendorId + "_" + effectiveDate);
form.submit();
return true;
},
"Cancel": function ()
{
$(this).dialog("close");
return false;
}
}
});
$myDialog.dialog('open');
}
</script>
As you see, the ID of the form is constructed of the literal "Form_" concatenated with the vendor ID and EffectiveDate keys, where the EffectievDate value was normalized into a value that could be used in an ID.
This all worked, but man, it looks ugly to me and very long winded, especially when I think how easy this could be done in WinForms in a no more than few lines of code. I am looking for a better way. I'm thinking this code has noob written all over it and I'd like to denoob it.

inline editing table / grid for for MVC

What is the easiest way to create a table where users can edit data directly (excel like) with minimum effort?
There are a lot of libraries and custom control but I am looking for something that is easy to implement and does not require a lot of coding.
In the controller create method for adding where you pass the parameter to with GET:
public bool EditData(int pkId, int statusID, string Comments)
{
// logic to edit
}
In your view add a table of data with your controls add the primary key to the ID of the control so that you can use it in jquery
<table class="table">
<tr>
<th>Status</th>
<th>Comments</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr class="searchable">
<td>
#Html.DropDownList("StatusID" + #Html.DisplayFor(modelItem => item.pkID), new SelectList(ViewBag.Status, "StatusID", "StatusTitle", item.StatusID), htmlAttributes: new { #class = "form-control", style = "width:100px" })
</td>
<td>
<textarea id="Comments_#Html.DisplayFor(modelItem => item.pkID)" rows="5" cols="20">#Html.DisplayFor(modelItem => item.Comments)</textarea>
</td>
<td>
<input type="button" class="btn btn-default" value="save" onclick='updateData("#Html.DisplayFor(modelItem => item.pkID)" )' />
</td>
</tr>
}
</table>
In the javascript add a call to the the edit method
function updateData(pkID) {
// the id of the drop down list is AssetEffectiveness + effectivnessid
var Status = $("#StatusID" + pkID).val();
var Comments= $("#Comments_" + pkID).val();
$.ajax({
url: "YOU_CONTROLLER_URL/EditData?pkId=" + pkID + "&statusID=" + Status + "&Comments=" + Comments,
cache: false
})
.done(function (data) {
if (data == 'True') {
// change bg of the tr
$("#Commects_" + pkID).closest('tr').css('background-color', '#eeffee');
// animate to indicate the save
$("#Commects_" + pkID).closest('tr').fadeOut(500).fadeIn(500);
// return color back after 2 seconds
setTimeout(function () { $("#Commects_" + pkID).closest('tr').css('background-color', ''); }, 1000);
}
else {
alert('not saved');
$("#Commects_" + pkID).closest('tr').css('background-color', '#ffcccc');
}
});
}

JSON Function - cascading DropDownList - update the model

Premise: I'm new with MVC, and my english is not perfect, I hope you'll understand my post, otherwise I'm here for explainations.
I'm working on a project created by another developer in ASP.Net MVC and I have this problem:
In a View I have two cascading DropDownList: one with the Distributors and the other with the Vendors of the Distributor selected in the first DropDownList.
This is the code:
In the Body:
<tr>
<td>
<span>Distributor</span>
</td>
<td>
#Html.DropDownList("DistributorID")
#Html.ValidationMessageFor(model => model.DistributorID)
</td>
</tr>
<tr>
<td>
<span>Vendor</span>
</td>
<td class="tdAlignLeft">
#Html.DropDownList("VendorCode")
#Html.ValidationMessageFor(model => model.ClientHeaderInformation.VendorCode)
</td>
</tr>
In the Script:
$("#DistributorID").change(function (e) {
var SelectGroupId =$(this).val();
$.getJSON('#Url.Action("VendorByDistributor", "ClientInfo")', { VendorGroup: DistributorID }, function (param) {
var vendorCodes = $('#VendorCode');
vendorCodes.empty();
$.each(param, function (index, param) {
vendorCodes.append(
$('<option/>')
.attr('value', param.vendorCode)
.text(param.vendorName)
);
});
});
});
In the Controller:
public ActionResult VendorByDistributor(int _DistributorID)
{
var Vendors = db.View_Vendors.Where(n => n.DistributorID.Equals(_DistributorID)).Select(
x => new
{
vendorCode = x.VendorCode,
vendorName = x.VendorName
});
return Json(Vendors, JsonRequestBehavior.AllowGet);
}
'View_Vendors' is a SQL Server view, mapped with Entity Framework, this is the SQL:
SELECT A.DistributorID, A.DistributorName, B.VendorName, B.VendorCode
FROM dbo.Distributors AS A LEFT OUTER JOIN dbo.Vendors AS B ON
A.VendorCode = dbo.Vendor.VendorCode
All seems to work well, but when I save the view sometimes the VendorCode property of the ClientInfo class hasn't the last selected value. This happens if I change The Distributor on the first DropDownList, in this case the second DropDownList (Vendors) gets the right values, but if I select a Vendor and then I save the model, the property VendorCode has still the first value.
I also tried to create a function to test the event 'change' of the Vendors DropDownList ...
$ ("# VendorCode.") Change (function (e) {
SelectId var = $ (this). val ();
$. getJSON ('# Url.Action ("updateVendorCode", "ClientInfo")', {VendorCodePass: SelectId});
});
... and in fact the event fires correctly only if I not change the Distributor and the Vendor items are not reloaded, in that case the event fires only the first time.
Sounds like a refresh problem of the second DropDownList Vendors, but I can't find the solution ...
Pileggi
I wrote a blog post about this here . Here is the relevant code that is similar to your case.
$("#ClientId").change(function () {
var clientId = "";
$("#ClientId option:selected").each(function () {
clientId += $(this)[0].value;
});
var url = '<%:Url.Action("ProjectList", "Client") %>' + "/" + clientId;
$.getJSON(url, null, function (data) {
var selectedValue = '<%:Model.ProjectId %>';
$("#ProjectId").empty();
$.each(data, function (index, optionData) {
if (optionData.OBJID == parseInt(selectedValue))
$("#ProjectId").append("<option value='" + optionData.ObjId+ "' selected='true'>" + optionData.Name + "</option>");
else
$("#ProjectId").append("<option value='" + optionData.ObjId + "'>" + optionData.Name + "</option>");
});
});
}).change();
Ok, sorry, it was a very trivial problem. The code is right, simply a field was wrong:
VendorCode in the place of VendorNumber... :-)
Sometimes you can't see the simplest solution ...
I don't delete the post, because the code is right and it could be useful for others.
Regards!
Pileggi

MVC: HTML table rows in a PartialView are not rendered in HTML after an Ajax call

My form looks like;
#model IEnumerable<SCD.ViewModels.UserLineViewModel>
#{
ViewBag.Title = "List";
}
<h2>List</h2>
<form method="GET" action="#Url.Action("AddNewUser", "DataService")" data-scd-ajax="true" data-scd-target="#userList">
#if (TempData["SuccessMessage"] != null)
{
<p class="successHighlight">#TempData["SuccessMessage"].ToString()</p>
}
#if (TempData["ErrorMessage"] != null)
{
<p class="errorHighlight">#TempData["ErrorMessage"].ToString()</p>
}
<p>
<input type="search" name="searchTerm" id="searchTerm" class="newUser"
data-scd-autocomplete="#Url.Action("AutocompleteUser", "DataService")" style = "width:300px;"/>
<input type="hidden" id="searchId" name="searchId"/>
</p>
<table>
<tr>
<th>Forename</th>
<th>Surname</th>
<th>Created</th>
<th>Administrator?</th>
<th></th>
</tr>
<tbody id="userList">
#Html.Partial("_UserLine")
</tbody>
</table>
</form>
My partial view looks like
#model IEnumerable<UserLineViewModel>
#Html.EditorForModel()
And the editor template so far looks like
#model UserLineViewModel
<tr>
<td>
#Html.DisplayFor(x => x.Employee.Forename)
</td>
<td>
#Html.DisplayFor(x => x.Employee.Surname)
</td>
<td>
#Html.DisplayFor(x => x.UserScd.Created)
</td>
<td>
#Html.EditorFor(x => x.UserScd.AdminFlag)
</td>
<td>
#Html.ActionLink("Remove", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
When the user selects a person from autocomplete, this method on the DataService controller gets called;
public ActionResult AddNewUser(int searchId)
{
var opStatus = this.UserScdRepository.Add(searchId);
if (!opStatus.Status)
{
return this.PartialView("_UserLine", new List<UserLineViewModel>());
}
this.TempData["SuccessMessage"] =
string.Format("You successfully entered the new user {0}",
vw_EmployeesAndJobTitles.GetName(searchId)).MessageTime();
var employeesInScd = this.EmployeeRepository.GetEmployeesInScd();
UserLineViewModel.UserScdRepository = this.UserScdRepository;
var userList = employeesInScd.Select(employee => new UserLineViewModel(employee)).ToList();
return this.PartialView("_UserLine", userList);
}
And the Jquery/Ajax that joins this up looks like;
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-scd-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
return false;
};
var showOtherTrade = function (data) {
$('#searchOtherTrade').val('');
$('#otherTradeList').html(data);
};
var updateAutocompleteForm = function (event, ui) {
var $input = $(this);
if ($input.hasClass("newUser")) {
$('#searchId').val(ui.item.id);
var $form = $input.parents("form:first");
$form.submit();
}
$input.attr('readonly', 'readonly');
$input.css('font-size', '11px');
$input.selectRange(0, 50);
}
};
var createAutocomplete = function () {
var $input = $(this);
var options = {
source: $input.attr("data-scd-autocomplete"),
select: updateAutocompleteForm
};
$input.autocomplete(options);
};
Now the problem I am getting is that when I return the PartialView in the controller, the data is not rendered in the HTML of the Partial View. So how do I fix this?

ASP.NET Mvc two dependent dropdownlist?

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.

Resources