Get Value from Textbox and Lookup using AJAX - c#

So right now i'm developing some software payroll project, and right now i'm stuck with this kind of problem [CLICK HERE FOR THE PIC] The example code for what i'm doing(Razor)
<td style="padding-right:10px;">
#(Html.DevExtreme().TextBoxFor(model => model.Cycle)
.ID("txtDay")
.Width(100)
)
</td>
<td>
#(Html.DevExtreme().LookupFor(model => model.WorkingShiftId)
.ID("lookupWorkingShiftId")
.DataSource(d => d.WebApi()
.Controller("WorkingShiftAPI")
.LoadAction("GetAllWorkingShift")
.Key("id")
)
.ValueExpr("id")
.DisplayExpr("name")
.Width(290)
)
</td>
<td style="padding-left:20px;">
#(Html.DevExtreme().Button()
.ID("btnGenerate")
.Type(ButtonType.Default)
.Text("Generate")
.OnClick("btnGenerate_OnClick")
//.Hint("Generate")
//.UseSubmitBehavior(true)
)
</td>
so what i want to do, is to get the value from the Textbox and the Lookup, and the Generate button for the trigger
#PS, currently in this project i'm using DevExtreme in Visual Studio and ASP.NET Core 2.0
UPDATE HERE PLEASE CHECK THE PIC
[HERE FOR THE PIC]
function btnGenerate_OnClick(data) {
var url = '#Url.Action("getCycleResult", "WorkingPattern")';
var Cycle = $("#txtDay").dxTextBox("instance");
Cycle.option("value", data.Cycle);
var WorkingShiftId = $("#lookupWorkingShiftId").dxLookup("instance");
WorkingShiftId.option("value", data.WorkingShiftId);
var confirmGenerate = true;
if (confirmGenerate == true) {
#*urlString = '#Url.Action("getCycleResult", "WorkingPattern")';*#
$.ajax({
url: url, // '#Url.Action("getCycleResult", "WorkingPattern")'
type: 'GET',
data: { Cycle, WorkingShiftId },
success: function (data) {
alert("in");
var dataWorkingPattern = $("#gridWorkingPattern").dxDataGrid({
dataSource: data,
columns: ["cycle","workingShiftId"]
});
}
})
}
}
So to make that happen i'm using AJAX to take the value from the Textbox and Lookup
[HttpGet]
public List<WorkingPatternDetail> getCycleResult(int Cycle, Guid WorkingShiftId)
{
List<WorkingPatternDetail> oWorkingPatternDetailList = new List<WorkingPatternDetail>();
for (var i = 1; i < Cycle+1; i++)
{
WorkingPatternDetail oWorkingPatternDetail = new WorkingPatternDetail();
oWorkingPatternDetail.Id = Guid.NewGuid();
oWorkingPatternDetail.Cycle = i;
oWorkingPatternDetail.WorkingShiftId = WorkingShiftId;
oWorkingPatternDetailList.Add(oWorkingPatternDetail);
}
return oWorkingPatternDetailList ;
}
and this the Controller after getting the value, (LOOPING) the value, and after that, i take the result and show the result in the #gridWorkingPattern (in the AJAX), (sorry about my english, and i'm new here)
UPDATE
I was trying to get the value from the Textbox and the Lookup but unfortunately the value doesn't get into the function, i can't even get the _btnGenerate_onClick_ function to work

You should first get the instance of the dx control which is in your case something like this:
var txtDay = $("#txtDay").dxTextBox().dxTextBox("instance");
var workingShift = $("#lookupWorkingShiftId").dxLookup().dxLookup("instance");
You than access values like this:
var day = txtDay.option("value");
var shiftId = workingShift.option("value");

Related

How to save table order row order after reordering it using kendo ui jquery? I dont know how to save the order into the database

// Kendo table sortable
var kendoSortable = grid.table.kendoSortable({
filter: ">tbody >tr",
hint: function (element) { // Customize the hint.
var table = $('<table style="width: 600px;" class="k-grid k-widget"></table>'),
hint;
table.append(element.clone()); // Append the dragged element.
table.css("opacity", 0.7);
return table; // Return the hint element.
},
cursor: "move",
placeholder: function (element) {
return $('<tr colspan="4" class="placeholder"></tr>');
},
change: function (e) {
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
});
Im trying to save the order after dragging and reordering. to the database so that when i reload the page the order where i have ordered it would be the exact order when i am reaordering it
Look into using the change event for the Sortable widget. This event provides the oldIndex and newIndex positions for the item that was moved.
Below is an example of one way to go about getting the reordered items and then sending that data to the server to save the changes. Hopefully, this will help you get started with solving your problem.
The change event firing indicates the item has been sorted and the item's position has changed in the DOM. Looking at the change event below, I'm getting the data items for the current page of the grid into currentGridView. Then I'm using the slice() method to get the items between the oldIndex and newIndex. Then I call the updateSequence function.
The updateSequence function creates an array to store objects to be passed to the server. These objects are based on the DataSequenceModel class. Basically, I just need to know the Id and the new sequence for each item that has been reordered. After this I'm using a basic Ajax POST to send the data to the server.
Index.cshtml - Here is a dojo based on Telerik's Integration - Grid demo and updated with my changes.
<div id="grid"></div>
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
// ...Basic grid setup
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function (e) {
// Get the indexes and data items that have been reordered.
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip;
var currentGridView = grid.dataSource.view();
var dataChanged = currentGridView.slice(oldIndex, newIndex + 1);
updateSequence(oldIndex, dataChanged);
}
});
});
function updateSequence(startIndex, dataChanged) {
// Create array to be passed to Controller. Based on DataSequenceModel class.
let data = [];
let newSequence = startIndex;
for (var i = 0; i < dataChanged.length; i++) {
data.push({ Id: dataChanged[i].ProductID, NewSequence: newSequence });
newSequence++
}
$.ajax({
type: "POST",
url: 'https://localhost:44395/Test/UpdateSequence',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (e) {
console.error(e);
}
});
};
</script>
TestController.cs
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public bool UpdateSequence(IEnumerable<DataSequenceModel> data)
{
// ...Logic to update sequence in database.
return true;
}
}
DataSequenceModel.cs
public class DataSequenceModel
{
public int Id { get; set; }
public int NewSequence { get; set; }
}

Get Dynamically Created TextBox ID From Razor To jQuery

I am trying to get the dynamically created TextBox ID into jQuery from Razor view. The IDs are created in HTML as follows:
Product - 1: cartDetails_0__Quantity
Product - 2: cartDetails_1__Quantity
Right now, when I give the above inputs directly to Ajax call, it updates the corresponding rows. As an example:
#if (ViewBag.Cart != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Id)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].IP)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate", data_id = cartDetails[i].Id })</td>
</tr>
}
}
var url = '#Url.Action("UpdateCart2")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + 0 + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert($('#cartDetails_' + 0 + '__Quantity').val());
});
Is there any way to loop through jQuery to get the dynamically generated TextBox ID in Razor? I've tried the following but doesn't get the value:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + i + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Even tried this one but it gets the value of first TextBox only:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $(this).val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Note: I am trying to update rows giving input to the TextBoxes with Ajax call. The TextBoxes are in a loop in the view. In this regards, I've to get the IDs of the dynamically generated HTML IDs.
You can use create event of dynamically created elements in order to get their Ids.
But bear in mind to use this you need to use On(). See http://api.jquery.com/on/
See also:
Event binding on dynamically created elements?
In jQuery, how to attach events to dynamic html elements?
PS. If there is a cleaner way to get dynamically created elements I would also be glad to get it :)
Edit. Maybe I was not clear enough . There is no exactly "create" event. You just can hook any actions you need to On()
See also jQuery "on create" event for dynamically-created elements

DropDownListFor get selected item value as parameter to controller

Problem
I want my Html form to pass the value of the selected DropDownListFor to the controller but I can't figure out why the controller is not taking any value.
Im sending the value to the controller and trying to do some code with the selected value each time the user selects something but i can't manahe myselft to do it.
View
#Html.DropDownList("Fechas", "Todas")
<div id="target">
</div>
Javascript
$('#Fechas').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
var datafecha = $(this).val();
});
$("#Fechas").change(function () {
var dateSelected = $("select option:selected").first().text();
$.get('#Url.Action("Index")',
{ id: dateSelected }, function (data) {
$("#target").html(data);
});
});
Controller
public ActionResult Index(string id)
{
var db = Context();
string dateday;
string lines;
List<string> listItem2 = new List<string>();
List<string> listadesumas = new List<string>();
foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
{
dateday = Convert.ToString(item);
lines = dateday.Split(' ')[0];
listItem2.Add(lines);
}
var fechas = new SelectList(listItem2.ToList());
ViewBag.Fechas = fechas;
////////////-------------------/////////////
if (id == //SOMETHING)
{
// To do code comes here, which takes selectGroup as parameter
}
////////////_----------------------////////////
return View("~/Views/HomePos/Index.cshtml",db.Pos.ToList());
}
So how can i get my selected id as a parameter to use it in my controler and change data on the view? im not fully atached to javascript so if you have other approaches i will appreciate any help

do I need getJson at all?

$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/

Dynamic Html.ActionLink in javascript?

Is there a way to add a Html.ActionLink through javascript?
For instance, I have this Edit function in my controller:
public ViewResult Edit(int companyID)
{
....
}
And I'd like to do something like this in javascript:
var id = $("#hdnID").val();
$("#editLink").html(<%: Html.ActionLink("Edit", "Edit", new { id }) %>);
A bit of a crude example, but it's basically what I'd like to do. Is it at all possible?
The id is a client script. You cannot mix server side script with client script. I am afraid that you are trying to submit HTML forms with action links instead of using submit buttons which is very bad. I see that you fetch the value of an input field with $("#hdnID").val() and then try to assign it to some action link and send to the server whereas if you used a simple submit button you wouldn't even need javascript. Your code would simply be:
<% using (Html.BeginForm("Edit", "Home")) { %>
<%: Html.HiddenFor(x => x.HdnId) %>
<input type="submit" value="Edit" />
<% } %>
Also it is clear that if you are using a hidden field it's because the user cannot change the value so an even simpler solution would be to directly generate the link you need:
<%: Html.ActionLink("Edit", "Edit", new { id = Model.SomeId }) %>
I haven't found a really good way yet. What I usually do is something like this:
var id = $("#hdnID").val();
var link = '<%: Html.ActionLink("Edit", "Edit", new { id = -999 }) %>';
$("#editLink").html(link.replace('-999', id));
The key is to select a value that id would never have in reality or exist otherwise in the link.
I found a handy way out of this problem thinking slighly out of the box. The reason I use ActionLink is really for an easy way to handle the routing. Simply supply Controller and action name and the helper generates the correct url. To get around this in JavaScript I first created an HtmlHelperExtender using the UrlHelper to resolve the url in proper context.
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static string ResolveUrl(this HtmlHelper html, string url)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
return urlHelper.Content(url);
}
}
}
Now in JavaScript it's easy enough to get the proper Url
$(document).ready(function () {
var action = '<%= Html.ResolveUrl("~/Controller/JsonAction") %>';
// JSON controller call for model data
$.getJSON(action, null, function (models) {
// Do something with models
action = '<%= Html.ResolveUrl("~/Controller/Details/") %>';
for (var i = 0; i < models.length; i++) {
$('#modelList').append(
'<tr><td>' + models[i].Title + '</td></tr>');
}
});
});
This is how I did it. You can use javascript replace.
var ul = document.createElement('ul');
if (data.EvidenceList != null) {
for (var i = 0; i < data.EvidenceList.length; i++) {
var li = document.createElement("li");
var evidenceId = data.EvidenceList[i].EvidenceId;
var evidenceName = data.EvidenceList[i].Name;
var candidateProgrammeComponentId = data.CandidateProgrammeComponentId;
var str1 = '#Html.ActionLink("dummyEvidenceText", "DownloadFile", new { candidateProgrammeComponentId = "dummyCandidateProgrammeComponentId", evidenceId = "dummyEvidenceId", evidenceName = "dummyEvidenceName" })';
var str2 = str1.replace('dummyEvidenceName', evidenceName);
var str3 = str2.replace('dummyCandidateProgrammeComponentId', candidateProgrammeComponentId);
var str4 = str3.replace('dummyEvidenceId', evidenceId);
var str5 = str4.replace('dummyEvidenceText', evidenceName);
li.innerHTML = li.innerHTML +str5 ;
ul.appendChild(li);
}
}
var element = document.getElementById('evidenceList_' + data.guidId);
$('#evidenceList_' + data.guidId).empty();
document.getElementById('fileUploadFreeStructure_' + data.guidId).value = '';
$('#freeTextArea_' + data.guidId).val('');
element.appendChild(ul);
The server side code (the C#) is ran on the server, and the result is sent to the client, where the client then executes the JavaScript. So as weird as it is, you have two different code environments bumping into each other but can't interact with each other very well.
I usually do something like this, although I'm open to better ways:
function SetUrl(id) {
var url = '<%: Html.ActionLink("Bar", "Foo") %>' + '?id=' + id;
return url;
}
This takes advantage of the fact that
/Foo/Bar/{id} is usually equivalent to /Foo/Bar?id={id}, depending on how your routes are set up.

Categories

Resources