I have built a MVC application to insert form data into DB. I used angularjs library with html5 & bootstrap.
Below is the some major lines in HTML.
form tag:
<form ng-app='MyData' ng-controller='DataController'>
Button ():
<input type="button" value="Submit" ng-click="addUser();" id="btnSubmitAddUsr" class="btn btn-success" />
Below is the ajax call using Jquery & angular js:
var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
$scope.addUser = function () {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($scope.usrFName, $scope.usrEmail, $scope.usrPhone, $scope.selectApp.id, $scope.usrRole),
url: '/Home/AddUser',
success: function (data, status) {
$scope.clear();
},
error: function (status) { }
});
};
});
C# method:
[HttpPost]
public JsonResult AddUser(string usrFName, string usrEmail, string usrPhone, string usrApp, string usrRole)
{
var db = new SchedulerEntities();
db.Users.Add(new User { Name = usrFName, Password = "testPwd", Email = usrEmail, Phone = usrPhone, ApplicationId = Convert.ToInt32(usrApp), RoleId = Convert.ToInt32(usrRole) });
db.SaveChanges();
return null;
}
The above C# methods gets called; but the parameters shows null. Also when I check the $scope variables from browser; the form values shows correct there.
Please suggest.
You generally don't want to use $scope as your model and instead create an object for your model on the scope...you'll run into some other issues with prototype inheritance the way you are currently doing it. When you use ng-model, you should always have a '.' in the expression.
You should also use $http instead of $.ajax (it'll handle the serialization for you and run a digest cycle when the call completes).
var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
$scope.form = {usrFName: '', usrEmail: '', usrApp: ''}; // initialize any other form variables
$scope.addUser = function () {
$http.post('/Home/AddUser', $scope.form)
.success(function(){$scope.clear();});
};
});
Related
I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward
Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}
My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution
I'm refactoring my ASP .net core project and I want to make use of some Ajax calls, but I'm facing the following problem: when I try to send a request to a method in a controller of my project but it doesn't work.
I have a modal with the following button:
<button onclick="reviewRestaurant(#item.RestaurantId)" class="btn btn-outline-primary">Add review</button>
the reviewRestaurant() function looks like this:
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let review = $('textarea').val();
let data = { restaurantId, rating, review };
$.ajax({
type: "POST",
url: `/Restaurants/Review`,
data: JSON.stringify(data),
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
And the method that I wanna call in the Restaurants controller looks like so:
[Authorize]
[HttpPost]
public async Task<IActionResult> Review(int restaurantId, string rating, string content)
{
var username = this.User.Identity.Name;
await this.restaurantsService.Review(restaurantId, username, rating, content);
return this.RedirectToAction("Details", new { id=restaurantID });
// the output of this method will be refactored later once I manage to get to it
}
The problem is I cannot reach the Review method in the controller. I get the 400 status code and I don't know how to fix it. I tried using DTO and [FormData] attribute for the method parameters and tried passing the data without stringifying it still nothing works.
If anyone can help me I would be very grateful. I'm relatively new to ajax calls and simply cannot see where my mistake is.
You can try this solution:
Create a common class for your parameters (int restaurantId, string rating, string content) and use FromBody. => Review([FromBody] YourClassName)
And write this parameters in your ajax code.
contentType: 'application/json; charset=utf-8',
data: 'json'
I hope it will help you.
Here is a working demo which I test.
#section Scripts
{
<script>
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let content = $('textarea').val();
let data = { restaurantId, rating, content };
$.ajax({
type: "POST",
url:'/Restaurants/Review',
data: data,
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
</script>
}
Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.
I need to pass data from View to Controller(From TestView1 to TestController2)
#Html.ActionLink("Text", "Index", "Sample", new { testId = test }, null)
Currently this is sending Data in QueryString. But i need to avoid this and pass data to Controller without Query string ?
How do i achieve without Querystring ?
I searched and most of them were by using Query string. If i missed out on solutions please redirect to correct path.
Thanks
Have you tried to post your data to the controller, if possible? Keeping a form and hidden fields..
e.g http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
You can send data using Ajax call back. try this method on your link/button
#* Your button/link *#
<input type="button" onclick='Link1()'" value="Submit" />
<script type="text/javascript">
function Link1() {
var Id = $("#txt").val();
$.ajax({
url: '#Url.Content("~/Test2/Actionname")',
type: 'post',
async: true,
data: { text: Id },
success: function (data) {
alert("Success");//Ajax request success
alert(data);//data from Test/yourAction
},
error: function (err) {
alert("fail");//Ajax request fail
alert(err.responseText);//error will displayed here
}
});
}
</script>
I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}