Calling Controller's method from Javascript in View - javascript

I am trying to access a method in the controller by Javascript from View
<div id="Historicaldata">
From Date <input type="date" id="fromDate" /> To Date <input type="date" id="toDate" />
Export to Excel
</div>
<script>
function GetFromDate() {
var dt1 = document.getElementById('fromDate').value;
var dt2 = document.getElementById('toDate').value;
var url = "~/GeneralStatics/Excel/" + "startdate=" + dt1 + "/endDate=" + dt2;
alert(url);
window.location.href = this.href + "startDate=" + document.getElementById('fromDate').value + "&endDate=" + document.getElementById('toDate').value;
return false;
};
</script>
In my controller there is avoid method like this:
public void Excel(DateTime startDate, DateTime endDate)
by which an Excel file will be downloaded.
what is the best way to do this?
and is it possible doing it without redirection?

You don't need javascript, you could put the input fields inside an HTML form instead:
#using (Html.BeginForm("Excel", "SomeControllerName", FormMethod.Post))
{
<div id="Historicaldata">
From Date <input type="date" name="startDate" />
To Date <input type="date" name="endDate" />
<button type="submit">Export to Excel</button>
</div>
}
Also make sure that your action arguments are matching the names of the input fields and don't forget that in ASP.NET MVC, contorller actions must return ActionResults, not void:
public ActionResult Excel(DateTime startDate, DateTime endDate)
{
...
}

Use AJAX to download the file:
$.ajax({
url: '#Url.Action("Excel", "GeneralStatics")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
type: "GET",
success: function () {
window.location = '#Url.Action("Excel", "GeneralStatics", new { #startDate= dt1 , #endDate = dt2 })';
}
});

Related

don't see Json data result in JSP

In my .JSP file i have :
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="submit" onclick="submitform()">
</form>
<p id="result"></p>
</body>
and my Javascript function is:
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
};
Also I created a new class User.java with some data, then in my Jsoncontent.java , in method POST I set my variables and created a request for json like this:
String jsonData = request.getParameter("per");
System.out.println(jsonData);
Gson gson = new Gson();
User data = gson.fromJson(jsonData, User.class);
System.out.println("Fetching json object");
String name = data.getName();
String address = data.getAddress();
System.out.println("User Name: "+ name );
System.out.println("User Address: "+ address );
User user = new User();
user.setName(name);
user.setAddress(address);
String jsonObj = gson.toJson(user);
System.out.println(jsonObj);
out.print(jsonObj);
So,all works without errors or warnings but I don't see the result when I click on submit button. I don't know why.
You note in the comments to the other answer that i still have a white browser page yet without name and address which indicates that the browser is navigating away from the page you are currently viewing and, therefore, you are not making an Ajax request - or more likely you are making an Ajax request but are also making a standard HTTP Post request due to the fact that you have not disabled the default submit event.
You therefore need to disable the default submit action.
https://api.jquery.com/event.preventdefault/
https://www.w3schools.com/jquery/event_preventdefault.asp
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" id="submit" type="submit">
</form>
<p id="result"></p>
</body>
$('#submit').click(function(e){
e.preventDefault(); //prevent standard post
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
})
You missed the point: you have $ajax but should be $.ajax
Also you can submit form instead of json, like:
function submitform(){
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
And in the servlet get the parameters "name" and "address":
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
...
String name = request.getParameter("name");
String address = request.getParameter("address");
...
}
CHANGES IN ANSWER
Sorry, I only paid attention to the conclusion of the alert message. Alan Hay is right in his remark, you can use it or change the type to a button.
Anyway, here is the working code
Servlet.java
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(urlPatterns = "/jsonserverlet")
public class Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String jsonData = request.getParameter("per");
out.print(jsonData);
}
}
index.jsp
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.js"
type="text/javascript"></script>
</head>
<body>
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="button" onclick="submitform()">
</form>
<p id="result"></p>
</body>
<script>
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
</script>
</html>

Why I cannot Login the using c# and mysql in ASP.net

I am beginner in developing a website using ASP.Net
Please Help me. so that i can pursue my career. Thanks in Advance
I am creating a login script using c# and I want to call it in javascript.
But it after I Logged in, The Login page will only refreshing.
And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll
So here is my code :
HTML
<form>
<div class="form-group">
<input type="text" class="form-control material" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control material" id="password" placeholder="Password">
</div>
<button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>
</form>
JAVASCRIPT:
$(document).ready(function () {
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
AuthenticateUser(username, password)
});
});
function AuthenticateUser(username, password) {
var value = "{'email':'" + username
+ "','pass':'" + password
+ "'}";
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: value,
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
C#:
[WebMethod]
public string loadEmployeeAccount(string email, string pass)
{
List<Auth> mylist = new List<Auth>();
using (MySqlConnection connection = new MySqlConnection(connectionString()))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = #email AND password = #pass", connection);
cmd.Parameters.Add("#email", MySqlDbType.VarChar).Value = email;
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = pass;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int user = 0;
if (dr["userType"].ToString() == "")
user = 1;
else
user = Convert.ToInt32(dr["userType"].ToString());
mylist.Add(new Auth
{
user_id = dr["user_id"].ToString(),
username = dr["username"].ToString()
});
}
dr.Close();
connection.Close();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsn = jss.Serialize(mylist);
return jsn;
}
And here is the image on the console.
Can someone help me with this?? any help will much be appreciated. Thanks
Okay, in order to achieve your functionality follow these steps:
In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:
data: {"json": JSON.stringify(value)}
Then decorate your class with:
[System.Web.Script.Services.ScriptService]
to allow POST requests via AJAX to your WebMethod.
And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:
[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"];
string password=jsondata["pass"]
//Your code here
}
it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod
function AuthenticateUser(username, password) {
var value = {'email':username,
'pass':password};
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: JSON.stringify(value),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.
First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.
type: ‘GET’
Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:
data: {
email: username,
pass: password
}
also, delete the dataType: ‘JSON’

Run a method in controller according to datepicker value

I want run the method Index in the Home Controller according to the date selected in datepicker,
Here is my View code:
<input type="text" name="date" class="datepicker" id="calendar" />
$("#calendar").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (date, instance) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home")/' + date,
success: function (data) {
if (data.success) {
alert(date)
}
}
})
}
}).datepicker("setDate", new Date());
I want when I choose a date in my datepicker run this Method:
[Route("Home/{date?}")]
public ActionResult Index( DateTime? date = null)
the problem is the Ajax call this URL: Home\12-04-2018when I choose the 12-04-2018 instead of /Home/Index/12-04-2018 is my code wrong or am I missing something? thanks for help.
Update your code as below, this should work for you. Date has been passed as query string
Script
$("#calendar").datepicker('setDate', 'today');
$("#calendar")
.datepicker({ dateFormat: 'dd/mm/yy' })
.on("changeDate", function (e) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home") + '?date='+ e.date,
success: function (data) {
if (data.success) {
alert(e.date)
}
}
});
});
And action method:
[HttpGet]
public ActionResult Index( DateTime? date = null)
Update:
To change the date format in view, build new date string from date object that C# can parse
var newDate = e.date.getUTCMonth() + 1 + '/' + e.date.getUTCDate() + '/' + e.date.getUTCFullYear() + ' 00:00:00';
and pass it as parameter to controller.

Ajax replace new arraylist without refresh page

I am new ajax, how can i replace ${phList} with new arraylist so that ajax can help me update the content without refresh whole page.
The ajax will trigger controller to retrieve data and store in arraylist then pass the arraylist to ajax. Ajax will update the content in jsp. Next step forEach loop will generate the column and checkbox with value if there have record retrieve from database.
Any solution and hope this solution can help others. Thanks!
myJsp.jsp
<select id="selected_year" name="selected_year" class="form-control">
<c:forEach var="line" items="${yearlist}">
<c:choose>
<c:when test="${refreshInd ge 0 and line eq refreshInd}">
<option selected="selected"><c:out value="${line}" />
</option>
</c:when>
<c:otherwise>
<option><c:out value="${line}" /></option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].startDate" class="form-control" value="${ph.startDate}" id="calendar1" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].endDate" class="form-control" value="${ph.endDate}" id="calendar2" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-2">
<form:checkbox path="phList[${PHstatus.index}].checkboxDel" value="" class="cbposition" />
</div>
</div>
<br>
</c:forEach>
After i change selected_year to trigger the ajax, it work well but :success function(response) cannot work. I want to remove the existing ${phList} and update with new arraylist by replace ${phList} show at above jsp.
myJavascript.js
$(function($) {
$("#selected_year").change(function(){
var selectedText = $(this).find("option:selected").text();
var $form = $(this);
var action = $form.find('.send').val();
var list[];
var array[];
$.ajax("holiday/pubholiday.json?" , {
method: "GET",
accepts: "application/json",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
$("#phList").remove()
$(JSON.stringify(response))
//how to pass the response which is my new arraylist to replace the ${phList}
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
.fail(function(jqXHR, textStatus, errorThrown) {
var errorMessage = "";
if (jqXHR.status == 401) {
errorMessage = "Your session has expired. Please login again.";
}else if(jqXHR.status == 500){
console.log(jqXHR.status);
console.log(jqXHR.responseText);
console.log(thrownError);
}else {
try {
var errorJson = JSON.parse(jqXHR.responseText);
errorMessage = errorJson.error;
} catch (e) {
errorMessage = errorThrown || textStatus;
}
}
});
})
});
This is object model store in the arraylist. Each record will contain object model data.
model.java
public class PubHoliday {
private int year;
private String holidayID;
private String holidayDesc;
private String startDate;
private String endDate;
private boolean checkboxDel;
private String selected_year;
private int refreshInd;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getHolidayID() {
return holidayID;
}
public void setHolidayID(String holidayID) {
this.holidayID = holidayID;
}
public String getHolidayDesc() {
return holidayDesc;
}
public void setHolidayDesc(String holidayDesc) {
this.holidayDesc = holidayDesc;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean getCheckboxDel() {
return checkboxDel;
}
public void setCheckboxDel(boolean checkboxDel) {
this.checkboxDel = checkboxDel;
}
public String getSelected_year() {
return selected_year;
}
public void setSelected_year(String selected_year) {
this.selected_year = selected_year;
}
public int getRefreshInd() {
return refreshInd;
}
public void setRefreshInd(int refreshInd) {
this.refreshInd = refreshInd;
}
}
First, you need to wrapper <c:forEach var="ph" items="${phList}" varStatus="PHstatus"> by div with id, example:
<div id="list_holidays">
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
.......
</c:forEach>
</div>
Then in success ajax code
- Empty div#list_holidays
- Get result, each row, create new div, append to div#list_holidays
success: function(response) {
var wrapper = $('#list_holidays');
wrapper.html('');
//->foreach response result
// -> $('div').html(your template).appendTo(wrapper)
}
JSP is server side rendering. meaning, when a request is received server uses the variable ${phList} to render a dynamic HTML page and sends that page to the browser. Ajax is a request made by your javascript sitting in browser. So, the browser has no way of knowing or changing the variable $(phList} directly and affecting the template.
However, what you said can be achieved. In one of following ways
Method 1 (easiest):
Implement holiday/pubholiday.asp which responds with only this instead of json.
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
...
<br>
</c:forEach>
Add a container element to the array items something like this
<div id="container" >
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
...
</c:forEach>
</div>
Change your ajax request in main page to this. When you get a response from pubholiday.jsp, replace contents of #container to what is received from ajax.
...
$.ajax("holiday/pubholiday.asp?" , {
method: "GET",
accepts: "application/html",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
// This is where magic happens
$("#container").html(response);
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
...
Method 2:
If you need the response to be only json, in success callback read the json, and generate html yourself by concatenating strings and then replace the #container element.
Method 3 (recommended):
User some client side rendering library like polymer or handlebars to render json into html.

LogIn Page Using JQuery

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}
You just need to remove
alert('b');``
on your jquery code
try adding a
return false
at the end of the ajax call
Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},
I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})
Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

Categories

Resources