C# WebApplication POST - javascript

I'm trying to POST a form using C#
I make some searches, however I couldn't code it right way (I am new in this field).
Here are my codes;
View;
<form>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="input-username" name="Username" required autocomplete="on" />
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" id="input-password" name="Password" required autocomplete="on"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" id="button-login">Log In</button>
</form>
Controller;
// GET: User
[HttpPost]
public ActionResult Login()
{
string username = Session["Username"].ToString();
string password = Session["Password"].ToString();
Service iLocationService = new Service();
var result = Service.MemberGetLogin( username, password, "127.0.0.1" );
ViewBag.Message = result;
return View();
}
Javascript;
jQuery(document).ready(function () {
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: "/Controllers/UserController/login/",
data: $(this).serialize(),
dataType: "json"
})
.done(function (result) {
console.log(result);
})
.fail(function (a) {
console.log( a);
});
});
});
What I am trying to do is POST the input values to chech the user.
Thanks in Advance

Look at this line
string username = Session["Username"].ToString();
In your code you are trying to read the username and password values from Session variables. Who set the user name and password to Session ? You should be reading those from the posted form and use that.
[HttpPost]
public ActionResult Login(string userName,string password)
{
// do something with userName and password and return something
}
Also, you need to make sure that you are serializing the form, not the button clicked. I personally prefer to use the Html helper method to generate the form tag and use the action attribute value of the form in my javascript code instead of hardcoding the urls.
So in my razor view
#using(Html.BeginForm("login","User"))
{
//Your existing form inputs goes here
<button class="button button-block" id="button-login">Log In</button>
}
and in the script
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: $(this).closest("form").attr("action"),
data: $(this).closest("form").serialize()
})
});
Since you are doing an ajax form submit, i suggest you return a json response which your client code can parse and do further things.
[HttpPost]
public ActionResult Login(string userName,string password)
{
//if userName and password are valid
return Json(new { Status="success"});
// else
return Json(new { Status="failed", Message="Invalid credentials});
}
and in your done callback, you should inspect this value and do further things
.done(function (result) {
if(result.Status==="success")
{
window.location.href="/Home/Index"; // change to wherever you want to redirect to
}
else
{
alert(result.Message);
}
})

Related

How to get Ajax form to work in asp.net core

net core and I'm building a to do list app to learn but iv hit a road block trying to add an item to a to do list with out refreshing the page.
With my current setup the controller method to add a todo item to DB and a script to get refresh the html on page are called on form submit but the html is updated before item is added to DB.
Any suggestions on how to fix this or what is the best way to go about doing this would be greatly appreciated.
My Div for Table:
<div id="tableDiv"></div>
My Input form:
<div id="addTodoForm">
<form asp-action="AddToDoForm" method="post" data-ajax="true" >
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
</form>
</div>
My Script To update html (has a time out function as a temporary fix to this issue)
<script>
$("#addTodoForm").submit(function()
{
setTimeout(function(){
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
})
}, 500);
})
</script>
My method to add Item to DB:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
if (ModelState.IsValid)
{
string currentUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
IdentityUser currentUser = _context.Users.FirstOrDefault(x => x.Id == currentUserId);
toDo.User = currentUser;
toDo.Status = false;
_context.Add(toDo);
await _context.SaveChangesAsync();
}
return BuildToDoTable();
}
Not sure what is your whole code, here is a simple working demo about how to post data to backend and display the data from backend without refreshing:
View:
#model ToDo
<div >
<form method="post" id="addTodoForm">
<input asp-for="Id" class="form-control "/>
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
//focus here...it is type of button and add an onclick event here.....
<input type="button" value="Create" class="btn btn-primary" onclick="PostData()" />
</form>
</div>
<div id="tableDiv"></div>
#section Scripts {
<script>
function PostData() {
$.ajax({
type: "POST",
data: $("#addTodoForm").serialize(), //using this way to get the form data
url: '/Home/AddToDoForm',
success: function (result) {
$('#tableDiv').html(result);
}
})
}
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
return PartialView("Partial", toDo);
}
}
Partial.cshtml(jsut a easy view for testing):
#model ToDo
#Model.Item //display the data
You can use e.preventDefault() which prevents the default behavior of submitting your form (refresh the page).
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
})
</script>
use this code:
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
location.reload();
})
</script>

How to receive data included file in asp.net core?

Which model should I use to receive a js data, included a File object and a string, from client? Or which data type should I use for File object in asp.net Core server?
Use ViewModel to receive the file and string , and submit form directly to post these data . Note : add enctype="multipart/form-data" in Form when you want to send files
public class TestViewModel
{
public string Name { get; set; }
public IFormFile file { get; set; }
}
<div class="row">
<div class="col-md-4">
<form asp-action="UploadFile" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="file" class="form-control" />
</div>
<div class="form-group">
<input type="submit" id="btnSubmit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
<span id="result"></span>
</div>
If you want to send form data by js , you could add id="fileUploadForm" and try the javascript like below
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
//enctype: 'multipart/form-data',
url: "/Home/UploadFile",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
</script>
}
Controller
[HttpPost]
public async Task<ActionResult> UploadFile(TestViewModel data)
{ }
Which model should I use to receive js data, including a File object and a string
ASP Net Core has the IFormFile container for this purpose. The data is held internally as a stream.
Your action signature for a string and a file would look like,
public IActionResult Action(IFormFile file, string name) { }
Note, the parameter names must match the form data names you use in javascript. I.e,
const fd = new FormData()
fd.append('file' , file)
fd.append('name', 'some string')
This documentation provides full usage examples.

Send POST request to REST API via javascript

First, I read somewhere that we should not use XMLHttpRequest.
Second, I am a newbie in Javascript.
Third, I created a webpage to submit email and password.
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
</form>
My check function is
function check() {
document.getElementById('message').innerHTML = "checking";
const url = "https://<hostname/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
This code is not working and just redirects me to the same page again and again.
Please help me understand what am I doing wrong.
The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.
To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:
<script>
document.getElementById('whatever-form-id')
.addEventListener('submit', check);
function check(e) {
e.preventDefault();
// and now anything else you want to do.
}
</script>
This will prevent your form from posting and it will execute your function instead.
There were some errors in your code as I've checked, please use it like this
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" id='new_password' >
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check(event)" name="Submit"><b>Submit</b> </button>
</form>
<script>
function check(event) {
event.preventDefault();
document.getElementById('message').innerHTML = "checking";
const url = "https://hostname/login";
const data = {"email" : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
</script>
Then test by changing your post URL to correct one whether working or not, for more testing use browser inspector tool to see your ajax request.
I've also put it on fiddle for your live testing http://jsfiddle.net/rajender07/xpvt214o/903616/
Thanks
1) Your validation function always returns true
2) When you use fetch..then, its promises can be executed later than return statement
So your form will be refresh again and again. You should return false, and manually submit the form with JavaScript when you get an onSuccess response.
<script>
function check(event) {
document.getElementById('message').innerHTML = "checking";
const url = "https://localhost:8080/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
alert(response.json());
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return false;
}
</script>
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" name="Submit"><b>Submit</b></button>
</form>
Update:
Page not refreshed, error message displayed:
Firstly, I would like to understand what is your object after getting the data from REST API.
Secondly, there are mistakes in the html code as well, you don't need to add onclick on the submit button when there you already have a onsubmit on the form element.
Solution,
change
onsubmit="check(event);"
function check(e) { e.preventDefault() ... } // you can remove the return true
just going off the top of my head here but you've set the Content-Type to application/json in the headers but your body is not an JSON string
try making your body match the headers by doing
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : JSON.stringify(data),
method : "POST",
mode : "cors"
};
EDIT
So after re-reading your question, I think what is happening is you've set your button to type of submit and what is happening is when you click on the button, your form is getting posted through the good old form post and your page gets refreshed from the postback.
If you want to handle form posts yourself using fetch, change your button type to button and the form should no longer actually post then everything else will be handled by your click event handler.
ps. while you're at it, you can remove the method and onsubmit attribute from your form tag as well
So your form should look something like this
<form>
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="button" onclick="check()" name="Submit"><b>Submit</b></button>
</form>

How to send values and image form javascript to controller in spring MVC

This is the jsp code,
Username: <input type="text" name="user_name"/>
File: <input type="file" name="profile_img" />
<input type="submit" value="Save" onclick="saveProfileData()"/>
And this is the javscript code,
function saveProfileData() {
var user_name = document.getElementById("user_name").value;
var profile_img = document.getElementById("profile_img").value;
$.ajax({
type: "POST",
url: /login/saveProfileData,
data:{
"user_name": user_name,
"profile_img":profile_img
},
success: function(response){
//other code
},
error: function(e){
//alert('Error: ' + e);
}
});
}
#ResponseBody
#RequestMapping(value="/saveProfileData", method=RequestMethod.POST)
public int saveProfileData(#RequestParam(required=false) String user_name, MultipartFile profile_img) {
System.out.println(user_name);
//int i = code for save profile data.
return i;
}
When I click on save button, It gives this error The current request is not a multipart request.
Why this is happening and how to fix this? How can I send the values with image?
Please anyone help me.?
Have you tried adding the encodingtype of the input field for the file, like such:
File: <input type="file" name="profile_img" enctype = "multipart/form-data"/>

Form data not being posted to controller when using AJAX

Ok so I have this form in my view:
<form id="MyForm">
<input type="text" name="myinput" />
<button type="submit" />
</form>
I have the following Javascript at the top of my view, which runs when the page loads:
<script type="text/javascript">
$(document).ready(
function () {
$("#MyForm").submit(
function () {
var url = "Home/TestAjax";
var dataToSend = $("#MyForm").serialize();
alert(dataToSend);
$.ajax
(
{
type: "POST",
url: url,
data: dataToSend,
success: function (data) {
alert(data);
}
}
);
return false;
}
);
}
);
</script>
The form is being serialised to ajax correctly, as verified by the alert box. Here is my TestAjax controller method:
[HttpPost]
public string TestAjax(string data)
{
return !string.IsNullOrEmpty(data) ? "Success" : "Failure";
}
The value being returned is Failure, because the AJAX isn't being posted back. What am I doing wrong here?
Thanks
The name of your input field is myinput not data. So make sure you have consistently named the argument of your action as well:
[HttpPost]
public ActionResult TestAjax(string myinput)
{
return !string.IsNullOrEmpty(myinput) ? Content("Success") : Content("Failure");
}
When you use $("#MyForm").serialize() this will return myinput=some_value where some_value is obviously the value that the user has entered in this input field.
And if you had 2 input fields in your form:
<form id="MyForm">
<input type="text" name="foo" />
<input type="text" name="bar" />
<button type="submit" />
</form>
you would of course write a view model:
public class MyViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
that your controller action will take as parameter:
[HttpPost]
public ActionResult TestAjax(MyViewModel model)
{
return !string.IsNullOrEmpty(model.Foo) ? Content("Success") : Content("Failure");
}
Also please notice that in ASP.NET MVC controller actions should return ActionResults, not strings or whatever.

Categories