Using Query string in MVC 3.0 - javascript

I am having some anchor tags in the page and I have to set them all a value in query string and then
trying to send it in controller can this be possible.Actually I have a hidden field on the page and that hidden field is set to a value
when somebody selects a user from auto complete of jquery. Now my Question is that I am able to set hidden field a value but how can I assign value of hidden
field to query string in an anchor tag. Please help me. I am trying in this way.
<div id="page">
<div class="note-row2">
<div class="form-left">
<input type="text" id="txt_Autocomplete" />
<input type="hidden" id="hdnPkClientId" />
</div>
<div class="form-right">
</div>
<div class="right-row">
<h3><a href="/GoToPage/Index?Client_ID="+"'$('#hdnPkClientId').val()'" >My Page</a></h3>
</div>
</div>
</div>
Here I am setting the value in hidden field
<script>
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/ClientHome/SearchClientDetail",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id,
data: item
};
}));
},
error: function (xhr)
{ }
});
},
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
</script>
I

in your html:
<a id="YOUR_A" href="/GoToPage/Index?Client_ID=" >My Page</a>
in your js:
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
$("#YOUR_A").attr("href", "/GoToPage/Index?Client_ID="+ui.item.data.Id);
}

Related

How can I serialize a form in JavaScript asp.net

I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.

Displaying all data from loop

I am able to fetch all my data from database successfully but only the last item in the array displays. What am I doing wrong?
HTML
#foreach($groups as $group)
<button type ="button" value="{!! $group->id !!}" id="btn" name="btn">{!!$group->name!!}</button>
<div class="panel">
<label for="myvalue"><input type="checkbox" id="myvalue" /> <span>Label text x</span></label>
</div>
#endforeach
JavaScript
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data: {
id: $(this).val(),
access_token: $("#access_token").val()
},
success: function (result) {
$.each(result, function (i, fb) {
$("label[for='myvalue']").text(fb.name);
});
}
);
This way you are replacing the label text, not creating labels. What you are looking for would be something like:
<div class="panel" id="labels_cotainer">
<label for="myvalue">
<input type="checkbox" id="myvalue" />
<span>Label text x</span></label>
</div>
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data:{
id: $(this).val(),
access_token: $("#access_token").val()
},
success:function(result) {
$.each(result, function (i, fb) {
$("#labels_cotainer").append('<label>'+fb.name+'</label>');
}
}
});
This code will append every label to your panel
You have to dynamically create new labels and add fb.name to it otherwise you will replace all values until the last value
success:function(result) {
$.each(result, function (i, fb) {
$("#outerDiv").append('<label>'+fb.name+'</label>');
});
}

save dynamic input form data into database kendo ui

i have populated dynamic input form fields. its populated successfully.i do not have an idea how to save data into database by using put/post api. as i used get api.
html code
<div id="renderform" class="form horizontal-form form-body">
<!-- container UL to host input fields -->
<div class="row" data-template="fieldsTemplate" data-bind="source:fields">
</div>
<!-- button to save changes -->
<button id="save" class="btn btn-circle btn-sm btn-default" type="button">Save</button>
</div>
kendo template
<script id="fieldsTemplate" type="text/x-kendo-template">
<div class="form-group">
<label class="control-label" data-bind="attr: { for: name}, text: ItemLabel"></label>
<div class="">
<input class="form-control-static" type="text" />
</div>
</div>
</script>
ajax function
<script type="text/javascript">
// retrieve the model from an API call
$.ajax({
url: crudServiceBaseUrl + "FormItemsDesign/GetFormItemsDesignList?parentid=" + formdesignid,
//url :"json.txt",
type: "GET",
dataType: "json",
success: function (model) {
// convert the JSON to observable object
var viewModel = kendo.observable(model);
// bind the model to the container
kendo.bind($("#renderform"), viewModel);
}
});
</script>
Post/Put api's will be like
url: crudServiceBaseUrl + "FormItemsDesign
type:Post
type:Put
please help me, how to make/use ajax function to call Post/Put to save/update data by each dynamic field into database. i appreciate your valuable time and effort thanks in advance.
After reading more articles finally I found this solution. Its working for me.
$("#save").on("click", function () {
$("#renderform input").each(function () {
var dataModel = {
parentid: $(this).attr("id"),
ItemOrder: "1",
ItemFieldType: "1",
ColWidth: "100",
RowHeight: "100",
ItemText: $(this).val(),
ItemLabel: $(this).attr("name")
};
$.ajax({
type: 'POST',
url: crudServiceBaseUrl + "FormsItem?firmid=" + firmid + "&createdby=" + clientid,
data: JSON.stringify(dataModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
alert("Data Saved successfully");
});

Knockoutjs foreach n rows check if dropdown has value

I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});
I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle

How to add the Default Item (--Select--) in dropdownlist in custom popup (via html data attributes)kendo Grid in asp

am using kendo inline and popup editing in a single grid
i used custom template for popup grid
<script id="customPopUpTemplate" type="text/x-kendo-template">
<form id="myForm" action="" method="post">
<div class="k-edit-field">
<input name="LoginName" class="k-textbox"/>
<span id="sta3" style="color: Red; font-size:medium;"> </span>
</div><div class="div">Login Name: </div>
`<div class="k-edit-field">`<br>
` <input name="Password" type="Password" class="k-textbox"/> `<br>
<span id="sta4" style="color: Red; font-size:medium ;"> * </span>
</div> <div class="div">Password: </div>
<div class="k-edit-field">
<input name="ScopeId"
data-bind="value:ScopeId"
data-value-field="ScopeId"
data-text-field="ScopeName"
data-source="DataSourceScopepopup"
data-role="dropdownlist" /> <span id="sta6" style="color: Red; font-size:medium ;"> </span>
</div>
<div class="div">Scope: </div>
</form>
var DataSourceScopepopup = new kendo.data.DataSource(
{
transport:
{
read:
{
url: "WebServices/Project.asmx/GetScopepopup",
data: "{}",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json'
},
parameterMap: function(options, operation)
{
if (operation == 'read')
return kendo.stringify(options);
}
},
schema:
{
data: function(Data)
{
return (Data.d);
},
model:
{
id: "ScopeName",
fields:
{
ScopeId: { type: "number"},
ScopeName: { type: "string"}
}
}
},
error: function(e)
{
var xhr = e[0];
var statusCode = e[1];
var errorThrown = e[2];
alert('DataSourceScope - ' + xhr + ', ' + statusCode + ', ' + errorThrown);
}
});
This is My coding How to Add the Default item --Select-- in dropdownlist?
Now i get only the Database items,,, how to i add it?
thanks in Advance!!
Add attribute data-option-label="--Select--" in your template
<input name="ScopeId"
data-bind="value:ScopeId"
data-value-field="ScopeId"
data-text-field="ScopeName"
data-source="DataSourceScopepopup"
data-role="dropdownlist"
data-option-label="--Select--" <!- display default value-->
/>
Since you are using a bound element, I would change either the SQL statement or the Service to add the value you want to the returned list of values.
Otherwise, you can use the databound event to add a new item to the list, something like this:
dataBound: function () {
if (DataSourceScopepopup.at(0). !== "--Select--") {
DataSourceScopepopup.insert(0, { ScopeId: 0, ScopeName: "--Select--" });
}

Categories