How to connect $.ajax-data from textbox input? - c#

I am looking for connect the input i search within textbox, into the $.ajax-data.
textbox id=textSearchTB.
(the whole idea from this function is to press search from textbox input, and display the result)
function getSearchRecipe() {
$.ajax({
url: "WebService.asmx/searchRecipe",
data: "{id:textSearchTB}",
type: "POST",
dataType: 'json',
contentType: "application/json; charset= tf-8",
success: function (data) {
var result;
if (data.hasOwnProperty('d')) {
result = data.d;
}
else {
result = data;
}
for (i = 0; i < result.length; i++) {
$("#searchResult").append("<div>'" + result[i] + "'</div>");
}
}
});
}
<div data-role="content">
<form id="searchF">
<input type="text" id="textSearchTB"/>
<input id="searchRecipeBTN" type="submit" value="חפש מתכון" onclick="getSearchRecipe()" />
</form>
<form id="searchResult">
</form>
</div>

To get the value in the search box, do:
var textInput = $('#textSearchTB').val(); // Jquery
then:
data: {id: textInput} // am assuming that the server side method contains an argument named "id"

Related

PartialView is not showing in Asp.net MVC?

I have an array which as the number(Id's of some tags) and I am passing this array to the action method using ajax call when this array passed to the controller action method(RawTagCreation) and then the numbers in this arrays are used to get data from database and then pass to another ViewModel object (rawTagVMs) and then I am returning the partial view with this ViewModel object. The problem is that the partial view is not showing?
Basically success event of ajax call is also not fired.
function selectedValues() {
var datas = [];
$('#search_to option').each(function () {
datas.push($(this).attr('value'));
});
console.log(datas);
if (datas.length > 0) {
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
else {
alert('Please Select One or More Raw Tags')
}
}
The action method is given here
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
foreach (var item in selectedTags)
{
var OldSourecTag = db.Real_Raw_Points.Where(x => x.Source_Tag_Id_Fk == item).FirstOrDefault();
var OPCTag = db.OPC_SourceTags.Where(x => x.Source_Tag_Id == item).FirstOrDefault();
if (OldSourecTag == null)
{
RawTagVM objToInsertRawTags = new RawTagVM();
objToInsertRawTags.Source_Tag_Id_Fk = item;
objToInsertRawTags.R_Tag_Name = "Provide Tag Name";
rawTagVMs.Add(objToInsertRawTags);
}
}
return PartialView("_Update_TagNames", rawTagVMs);
}
return View();
}
PartialView is here
#model List<OmniConnect.ViewModel.RawTagViews.RawTagVM>
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Update The Raw Tag Names</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="Confirm()">Confirm Update</button>
</div>
when you try ajax call
you can't return partial view
if you want return a view you must use form like Html.Beginform
and submit
if you want return success method you must return a value may be string
and append it to a tag
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
return Json("<div>any view</div");
}
return json("");
}
and then you can use like this:
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});

Calling a linkbutton click with jquery

I've got a textbox, I want a function to be called onkeyup, for that reason I've got a hidden button that is trying to redirect to another c# function. The problem is jquery goes inside the function, but then doesn't go to the server side event.
Here's my HTML for both elements:
<div class="row" style="margin-top: 5px;">
<div class="col-sm-12">
<div class="input-group input-group-sm">
<span class="input-group-addon">Име:</span>
<asp:TextBox ID="tbCliName" ClientIDMode="Static" runat="server" onkeyup="runQuery(this)" CssClass="form-control"></asp:TextBox>
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
<span class="input-group-addon">Егн/Булстат:</span>
<asp:TextBox ID="tbEgnBStat" ClientIDMode="Static" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
Here's my jquery funtion:
function runQuery(e) {
$('#hiddenButton').click();
}
And the C# for the button click:
protected void hiddenButton_Click(object sender, EventArgs e)
{
AutoComplete_Press(tbCliName.Text);
}
EDIT with Ajax:
function runQuery(e) {
var search = $(e).val();
function runQuery(e) {
var search = $(e).val();
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'aapplication/json',
data: '{searchClause:' + search + '}',
dataType: 'json',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause)
{
int searchType = 0; //ЕГН
int csKind = 0;
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
//if (rbLP.Checked)
// csKind = 1;
string clients = laboratory.getClients2(searchType, searchClause, 1);
}
try using webmethod. In server side
[WebMethod]
public static void BindData()
{
AutoComplete_Press(tbCliName.Text);
}
And in client side
$("#hiddenButton").click(function() {
$.ajax({
type: "POST",
url: "index.aspx/BindData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({/*pass values here*/}),
dataType: "json",
});
});
Refer below link
https://www.aspsnippets.com/Articles/Calling-server-side-methods-using-JavaScript-and-JQuery-in-ASP.Net.aspx
The reason why it is not working is that you are using asp:LinkButton which is rendered as a element with href attribute set to javascript:__doPostBack().
If you replace asp:LinkButton to asp:Button calling $('#hiddenButton').click(); will start to work.
Just change this line of code
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
to this
<asp:Button ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:Button>
You can invoke function like this but not event
Create a Web Method and try Jquery Ajax
var params = {
url: 'Index.aspx/YourWebmethod',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: JSON.stringify(data to be send ),
success: function (result) {
alert('Success');
},
error: function (result) { alert('Warning! It failed.'); }
};
$.ajax(params);

Pass parameter from View to controller MVC 4

I want to pass selected value of dropdownlist from view to controller in html.BeginForm in MVC 4.
I can pass value of query string, but I have no idea about how to pass selected value of dropdownlist.
All suggestions are most welcome.
Here is my code attached
<form>
<fieldset class="form-group" id="ddl2">
<label for="exampleSelect1">Section Type:</label>
#(Html.Kendo().DropDownList()
.Name("ddlsection")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("--Select--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSectionType", "LookUp");
});
})
.Events(e => e.Change("onChange_ddlsection"))
.HtmlAttributes(new { #class = "form-control" })
)
</fieldset>
</form>
<div class="WordClass">
#using (Html.BeginForm("GetConditionListingInWord", "Inspection", new { sectionId = 'What should be here?' }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="Submit1" type="submit" value="" class="WordClassA tooltipSource" title='Print List in MS-Word format' data-placement='bottom' data-toggle='tooltip' />
}
</div>
I want 'ddlsection' dropdown's selected value in 'What should be here?' section.
You can pass Kendo Dropdownlist's selected value to the Controller using Ajax call and then redirect to another Action if you want as shown below:
<script type="text/javascript">
$(function () {
//Returns Dropdownlist's selected values to the Controller
$("#btnSubmit").click(function (e) {
e.preventDefault();
var data = {
ProjectID: $('#ProjectID').val(), //parameter I
IssueID: $('#IssueID').val() //parameter II
}
$.ajax({
type: "POST",
url: "/Controller/Action",
cache: false,
data: JSON.stringify(data),
dataType: this.dataType,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Variable data contains the data you get from the action method
window.location = "/Controller/OtherAction/" + data
},
error: function (data) {
$("#error_message").html(data);
}
});
});
});
</script>
For that you have to make AJAX call to your controler method
var userModel = {
RoleId: $("#drpRoleId").data("kendoDropDownList").value(),
}
$.ajax({
url: '#Url.Action("AddEditUser","User")',
type: 'POST',
data: JSON.stringify(userModel),
async: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});

How to send files to webmethod along with other data? Without using any plug in

Ok so I have a couple of input fields etc I send the data of these field to server side webmethod . WHich is working fine. But I also want to send files to the same webmethod (and not ashx hander) alond with the data of other input fields. Can you please help me out?
This calls webmethod which stored data in database
function SendToServer(name,lineitems) {
$.ajax({
type: "POST",
url: "test.aspx/PostDataWM",
data: JSON.stringify({ name: name,lineitems: lineitems }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
// console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
File Upload MarkUp
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<script type="text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" class="clsFileUpload" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
WebMethod
[WebMethod(enableSession: true)]
public static string PostDataWM(string name,string lineitems)
{
//blah blah
}
No need to stringify the data.
Try it directly. You can get data at your code level
type: "POST",
url: "test.aspx/PostDataWM",
data: { name: name,lineitems: lineitems },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,

Ajax : passing input box value to C# codebehind

I have an AJAX almost working. I can get it to execute a simple function and return a value such as the date and time.
My problem now is developing the script to send the value of an input box to the C# function and then using this value in the code. So that a the correct string can be returned.
If sombody could check if am doing it right or where am going wrong then that would be great
thanks
Ajax Code
$(document).ready(function ste() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
var thePostCode = $('#ContentPlaceHolder1__postCodeInput').val();
$.ajax({
type: "POST",
url: "Add-Property.aspx/GetAverageRent",
data: { PostCode: thePostCode },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("code was executed");
codeAddress();
}
});
});
});
C# Function Code
[WebMethod]
public static string GetAverageRent(string PostCode)
{
string Postcode = PostCode;
var webGet = new HtmlWeb();
var doc = webGet.Load("http://www.webaddress.com" + Postcode);
HtmlNode AvgPrice = doc.DocumentNode.SelectSingleNode("//div[#class='split2r right']//strong[#class='price big']");
if (AvgPrice != null)
{
return AvgPrice.InnerHtml.ToString();
}
else
{
return "Invalid Postcode!";
}
}
Markup
<div class="form-group">
<label for="_postCodeInput">Post Code: </label>
<input type="text" runat="server" id="_postCodeInput" onchange="ste()" class="form-control"/>
<asp:RequiredFieldValidator ID="_pcodeRFV" runat="server" Display="Dynamic" ControlToValidate="_postCodeInput" ValidationGroup="saveProperty" ErrorMessage="Property Postcode" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<div id="Result">Click here for the time.</div>

Categories