Display image immediately after fill textbox - c#

I want to display an image immediately after fill the textbox, don't need to click any button for get the picture.
I did this in my view:
#using (Html.BeginForm())
{
<input value="" id="UserID" name="UserID" type="text" class="form-control" />
<img id="CaptchaImg" alt="Captcha" src="#Url.Action("showFoto", "loan")" style="" />
}
<script language="javascript" type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("showFoto", "loan")',
datatype: "image/jpg",
success: function (UserID) {
$('#CaptchaImg').attr('src', UserID);
}
});
</script>
In my controller Loan.cs:
[HttpPost]
public string showFoto(string UserID)
{
string ImageID = UserID;
var virtualPath = string.Format("~/images/profile/{0}.jpg", ImageID);
if (System.IO.File.Exists(Server.MapPath(virtualPath)))
{
return virtualPath;
}
return null;
}
My information was from:get a image through jquery ajax
Please, need your helps... thanks!

Change your script to handle the .change event of the textbox and pass its value to the sever method (note the change event occurs when the textbox loses focus)
$('#UserID').change(function() {
$.ajax({
type: "GET",
url: '#Url.Action("showFoto", "loan")',
data: { userID: $(this).val() }, // pass the value of the textbox to the method
datatype: "image/jpg",
success: function (UserID) {
$('#CaptchaImg').attr('src', UserID);
}
});
});

Related

How to pass array HTML elements to AJAX POST to C# controller

I have this form in HTML.
<input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">
myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName
document.getElementById('myForm').onsubmit = function ()
{
var model = new FormData();
model.append("myID", $('#myID').val());
model.append("myName", $('#myName').val());
$.ajax({
url: "/MyController/MyMethod",
type: "POST",
data: model,
contentType: false,
processData: false,
success: function (response) {
Do_Something_Here;
},
error: function (xhr, error, thrown) {
alert(xhr.responseText);
}
});
}

How do I update an Unordered List with values after a Live search in c# mvc code?

I want to do a live search to filter results as I type in the textbox. There is a html Unordered list that is populated from the model when the page is loading and those are the items I want to filter when searching. Problem is how do I update the ul with the search values?
The cshtml page:
<div>
<input id="search" type="text" placeholder="Search Sections">
<ul id="menuList" style="max-height: 800px; overflow:scroll;">
#foreach (var item in Model)
{
<li>
<div style="display:inline-block; min-width:15%">#item.Index</div>
<div style="display:inline; min-width:80%">#item.Title</div>
</li>
}
</ul>
</div>
The ajax call:
$(function () {
$("#search").keyup(function (e) {
var s = $("#search").val();
$.get("/Document/GetSearchItem?searchString=" + s, function (r) {
//how do I update ui with results here?
});
});
});
The controller method that query's the db and returns a list that I use to update the model, this works well.
public async Task<IActionResult> GetSearchItem(string searchString)
{
var lst = await _sectionService.GetSearchString(searchString);
var documentModel = new List<DocumentViewModel>();
foreach (var item in lst)
{
documentModel.Add(new DocumentViewModel
{
Id = item.Id.ToString(),
Title = item.Title,
Index = item.IndexNumber
});
}
return View(documentModel);
}
In the controller:
public ActionResult Index()
{
return View();
}
public JsonResult Refresh(string search)
{
return Json(Records(search), JsonRequestBehavior.AllowGet);
}
private List<DocumentViewModel> Records(string search)
{
var list = /* your code to obtain records */;
return (String.IsNullOrEmpty(search)) ? list : list.Where(r => r.Title.StartsWith(search)).ToList();
}
The Index.cshtml:
#*
There is no data model here - the jQuery is working excellent for this example.
*#
<!DOCTYPE html>
<script>
window.onload = function () {
Refresh();
}
function Refresh() {
var search = document.getElementById("search").value;
$.ajax({
type: "GET",
url: '#Url.Action("Refresh", "Home")',
contentType: "application/json;charset=utf-8",
data: { search },
dataType: "json",
success: function (data) {
$('#menuList').empty();
for (var i = 0; i < data.length; i++) {
$('#menuList').append('<li><div style="display:inline-block; min-width:15%">'
+ data[i].Index + '</div>'
+ '<div style="display:inline; min-width:80%">' + data[i].Title + '</div></li>'
);
}
}
});
};
</script>
<html>
<body>
<div>
<input id="search" type="text" placeholder="Search Sections" onkeyup="Refresh()">
<ul id="menuList" style="max-height: 800px; overflow:scroll;">
</ul>
</div>
</body>
</html>
I was having similar kind of functioanlity in one of my asp.net projects and handled the ajax call this way. Check if it helps.
function SearchText() {
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "samplepage.aspx/samplemethod",
data: "{'searchValue':'" + document.getElementById('#search').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Match");
}
});
}
});
}
You will just have to use jQuery to do it manually.
Check this answer for some ideas: How to add items to a unordered list <ul> using jquery
You need to give the li a dynamic id
<li id="li_#item.Index">
and in filter function hide all li items under ul,
then loop the result to show selected items

Pass data from view to controller using AJAX in C# ASP.NET Core MVC

I have tried looking at answers to similar questions and none of them work for my code. I have tried a lot of different things, all it should do is post the fullname and then display it back in the view.
The view code:
<script type="text/javascript">
$(document).ready(function () {<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = {fn : fullName};
$.ajax({
type: 'POST',
url: '/demo/demo2/',
contentType: 'application/json',
data: JSON.stringify(payLoad),
success: function (result) {
$('#result2').html(result);
}
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
The controller code:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
First, when you pass string by ajax to action,you should ensure the received parameter name is the same as the incoming parameter name.
So, you should change var payload = {fn : fullName}; to var payload = {fullName: fullName};, or change public IActionResult Demo2(string fullName) to public IActionResult Demo2(string fn).
Then, because you passed only a string not an object parameter , so you don't need to use JSON.stringify, and remove contentType: 'application/json' .
Here is the detailed code:
<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = { fullName: fullName }; // change name
$.ajax({
type: 'POST',
url: '/demo/demo2/',
// contentType: 'application/json', // remove this line
data: payload, //remove JSON.stringify
success: function (result) {
$('#result2').html(result);
}
});
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
Controller:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
Here is the test result:

Submitting a cshtml form using ajax

#{
var db = Database.Open("CMS");
//retrieving the username of the user from the session
var session_username = Session["session_username"];
//get the details of the user from the database
var getuserdetailscommand = "SELECT * from student where student_username = #0";
var getuserdetailsdata = db.Query(getuserdetailscommand, session_username);
var statusfirstname = "";
var statuslastname = "";
var statusavatar = "";
foreach(var row in getuserdetailsdata){
statusfirstname = row.student_firstname;
statuslastname = row.student_lastname;
statusavatar = row.student_avatar;
}
//on submit execute the following queries
if(IsPost){
if(Request["button"] == "sharestatus"){
//retrieve the data from the form input fields
var statusbody = Request.Form["statusbody"];
var statususername = session_username;
//insert the status for the username into the database
var insertcommand = "INSERT into status(status_body, status_date, status_username, status_firstname, status_lastname, status_avatar) VALUES (#0, #1, #2, #3, #4, #5)";
db.Execute(insertcommand, statusbody, DateTime.Now, session_username, statusfirstname, statuslastname, statusavatar);
}
}
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function get() {
$.post('statusupdateform.cshtml', { name: form.name.value }
}
</script>
<form class="status-form" role="form" action="" enctype="multipart/form-data" method="post" name="form">
<div class="form-body">
<div class="form-group">
<textarea class="form-control" placeholder="What's on your mind?" name="statusbody"></textarea>
</div>
</div>
<div class="form-footer">
<div class="pull-right actions">
<button class="btn btn-primary" name="button" value="sharestatus" onclick="event.preventDefault();get();return false;">Share</button>
</div>
</div>
</form>
This is the code in my cshtml file. I want to submit the form using ajax so that the whole page doesn't get refreshed everytime a user submits anything.
The C# code necessary to run the form is also provided in the code.
Any help how can I submit the for using ajax?
Thank you!
Use Javascript or JQuery for this.
E.g. add script tag with link to jquery code file and then use $.get or $.post to make ajax call.
You should remove
method="post"
From the form as this will make the full page submit. Also you can find more information on how to do this in the Jquery documentation.
See the bottom of this link for an example:
http://api.jquery.com/jquery.post/
Use This to perform your operations
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});

data not displaying on form on ajax success

I am trying a simple task of displaying student name in a textbox based on StudentId entered. I am able to display the student name as an alert from jQuery - AJAX call but not in the text box, what am I missing here?
Controller:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult DisplayStudentName(string id)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudents.Where(a => a.StudentNumber == id)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
return Json(new { Name = StudentName });
}
jQuery:
$(function () {
$('#submitButton').click(function () {
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
alert(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
});
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="Data" style="text-align: left; height: 202px;">
Student Number:<input type="text" name="id" id="id"/><br />
Student Name:<input type="text" name="StudentName" id="StudentName"/><br />
<br />
<div id="Div1">
<button id="submitButton" name="submitButton" style="width:140px;">Display Short Name</button>
</div>
</div>
</asp:Content>
Again, I am able to display Student Name in the Alert window, but not in the text box, Am I missing something?
Thanks in advance
You need to prevent the default behavior of submit button. You can use the jQuery preventDefault function to do this,
$(function () {
$('#submitButton').click(function (e) {
e.preventDefault(); //prevent default behaviour
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
})
When preventDefault method is called, the default action of the event will not be triggered. So in this case the form submission will not happen ( so the page wont be reloaded).

Categories

Resources