Need to send a hidden input value to mvc controller using angularjs - c#

I have a hidden input field that contains a value I need to send my mvc controller.
$http({ method: 'GET', url: '/User/GetProjectsList' })
.success(function (data, status, headers, config) {
$scope.workflow = [];
$scope.Projects = data;
})
.error(function (data, status, headers, config) {
alert('error');
});
And the hidden field is:
<input type="hidden" ng-model='ProjectId' value="{{ProjectsObj.IDWorkflow}}"></input>
How can I send the value to the my controller and how do I get it in the controller? This is the method I had on the MVC controller.
[HttpPost]
public JsonResult GetProjectsList()
{
return Json();
}

Have you tried with query string ?
var pID=$scope.ProjectId
$http({ method: 'GET', url: '/User/GetProjectsList?ProjectID='+pID}).
success(function (data, status, headers, config) {
$scope.workflow = [];
$scope.Projects = data;
}).
error(function (data, status, headers, config) {
alert('error');
})
;

I hope this helped you ;)
app.controller("myCtrl", function($scope) {
$scope.formDetails = {};
$scope.sendToApi = function(){
var model = {
id: $scope.formDetails.id //this is my hidden input
name: $scope.formDetails.name,
}
//and then send your model to API
}
})

#Html.HiddenFor(m => m.ProjectId)
You Can Simply Pass Hidden Value To Controller From View By using model value like above syntax.

It seems like AngularJS does not take in consideration hidden input when submitting forms, check this issue for more details. But you can get your value in 2 ways:
classic way:
remove ng-model since has no sens with hidden type as explained above and add id:
<input id="project_id" type="hidden" value="{{ProjectsObj.IDWorkflow}}"/>
in Javascript side you simply do:
var project_id = document.getElementById('45').value;
AngularJS way
since Angular ignores hidden elements, you can replace it with type=text and display:none:
<input type="text" name="project_id" ng-model="projectID" style="display: none;"/>
and your javascript side using two way data-binding you can acces your ng-model variable:
var project_id = $scope.projectID;

Related

Using Action in Controller every 10min [duplicate]

I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;

Can't call new page by controller in Asp.net

I want to call new page by click on a button by jQuery from Index.cshtml :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
}
});
});
});
It call to my controller action : UserController/getAll
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return View("AllUser");
}
But is still at Index.cshtml not go to AllUser.cshtml page? I don't know why...please help.
UPDATE :
my jquery function call my action in controller , and the action work correctly but it not return to AllUser.cshtml page.
Please check out the documentation here. I would attempt using a tag-helper in the Ajax setup like this:
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: '#Url.Action("User", "getAll", new { id = "ID", name = "searchName" })',
id : idser,
success: function() {
alert("success");
}
});
});
});
Firstly I don't know what is your purpose behind using ajax while your are redirecting the other page ?
But you if still want to use Ajax, you can achieve this by two ways:
1) you can assign window.location in your success block.
2) Use your code by following way :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "GET",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
return true;
}
});
});
});
you can try it by putting return true in your script.
hope it helps to you
Updating in response to clarification in comments:
In the success callback,
location.href="/user/getall";
That will cause the browser to navigate to that URL after the ajax post has completed.
A button that posts a value from an input to another page - that's a form.
<form action="/User/getAll">
<input type="submit" value="Click me">
</form>
I don't know where your id is coming from, but you can put a hidden input in the form and a script to populate it (unless it's a user input - then you can just put the input right in the form.)
<form action="/User/getAll">
<input type="submit" value="Click me">
<input type="hidden" name="id" id="hiddenId"/>
</form>
<script>
$("#hiddenId").val($("#Name").val());
</script>
Or, if you want to be sure that your form's action URL matches your route:
<form action='#Url.Action("getAll", "User")'>
(Assuming that the controller is called "User".)
Here we go:
window.location.href = "yourUrl" can help you.
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
window.location.href ="../yourUrl"; //This is working!
}
});
});
});
You may redirect in Controller this like:
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return RedirectToAction("NameOfAction"); //Here is going Name of Action wich returns View AllUser.cshtml
}
Hope it helps;)

How to pass a JavaScript Array to ASP.Net MVC Action as part of post

I have a cshtml as follow,
DoPost.cshtml
#using (Html.BeginForm("Purchase", "PurchaseOrder", FormMethod.Post, new { #id = "frmPurchase" }))
{
// statements
// statements
<input type="button" id="submitPurchase" onclick = "myPurchase()" value="Select" />
}
In Javascript I have an array strings in variable "ExtraItems"
ExtraItems[0] ="123"
ExtraItems[1] ="124"
ExtraItems[2] ="125"
My Action which accept the data is as follows,
public ActionResult Purchase(PurchaseOrderModel model)
{
//Do some stuff with the passed data
return View("Purchase", model);
}
In the above PurchaseOrderModel, I have the property
public string[] SelectedProducts { get; set; }
to accept the Javascript Array elements.
What I tried:
The simple post did not work as the JavaScript array elements are not part of the Form elements,I couldn't use a #Html.HiddenFor because it is an array.
Hence tried to do an Ajax post under function myPurchase(),
$a.post('#Url.Action("Purchase", "PurchaseOrder")', { SelectedProducts: ExtraItems });
Here I did not get the ExtraItems details under model.SelectedProducts in the action. The biggest issue was i wanted to load the Purchase.cshtml View from the action, instead I got the controll back to the Jquery Post.
Please help me how can I solve this.
You should post your javascript array as a json object. You use the JSON.stringify() method converts a value to JSON. Something like :
$.ajax({
url: '#Url.Action("Purchase", "PurchaseOrder")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
SelectedProducts: ExtraItems
})
});
Here is my example for solving your issue
-----------------------------------------
//Script
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script>
var ExtraItems = ["aa","bb","cc","ff"];
function a()
{
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
alert( 'Sucs' );
}
} );
}
</script>
<button onclick="a();">click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
//Controller
[HttpPost]
public ActionResult Index( string[] SelectedProducts )
{
return View();
}
Take a string property in your model and then send the data as comma separated string
var dataToSent = ExtraItems.join(',')
If you have a property named Datum of type string in your model Purchase then the data to be sent will be, passing model
data : 'Datum=' + dataToSent
In your action you can split data into array
also for return response you have to redirect the page in the success function of your ajax call
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
window.location.href = "/controller/action" <--your url
}
} );
Use $.ajax function with the option traditional:true for enabling ASP.NET MVC default model binding for the list of string items.

Search method issue

I'm using MVC 5, C# and I'm trying to build a search filter that will filter through upon each key stroke. It works as so, but the textbox erases after submitting. Now this is probably not the best approach to it either. Is there a way to make so when it posts it doesn't erase the textbox, or better yet, is there a better alternative?
#using (Html.BeginForm("Index", "Directory", FormMethod.Post, new { id = "form" }))
{
<p>
Search Employee: <input type="text" name="userName" onkeyup="filterTerm(this.value);" />
</p>
}
<script>
function filterTerm(value) {
$("#form").submit();
event.preventDefault();
}
</script>
I agree with the comments on your question. Posting on every key stroke would be a frustrating user experience.
So, two answers, use ajax to perform the search (which will then keep the value since the whole page will not post) or have a submit button and name the input the same as the controller action parameter.
Controller code (used with your existing code):
public class DirectoryController : Controller
{
[HttpPost()]
public ActionResult Index(string userName)
{
// make the input argument match your form field name.
//TODO: Your search code here.
// Assuming you have a partial view for displaying results.
return PartialView("SearchResults");
}
}
View Code (to replace your code with Ajax):
<p>
Search Employee:#Html.TextBox("userName", new { id = "user-name-input" })
</p>
<div id="results-output"></div>
<script type="text/javascript">
$("#user-name-input").change(function(e) {
$.ajax({
url: '#Url.Action("Index", "Directory")'
, cache: false
, type: "post"
, data: {userName: $("#user-name-input").val() }
}).done(function (responseData) {
if (responseData != undefined && responseData != null) {
// make sure we got data back
$("#results-output").html(responseData);
} else {
console.log("No data returned.");
alert("An error occurred while loading data.");
} // end if/else
}).fail(function (data) {
console.log(data);
alert("BOOOM");
});
}
</script>
A better way is to ditch your Html.BeginForm (unless you actually need it for something else) and use a pure ajax method of getting the data.
So your modified html would be:
<p>
Search Employee:
<input type="text" name="userName" onkeyup="filterTerm(this.value);" />
</p>
<script>
function filterTerm(value) {
$.ajax({
url: '#Url.Action("Index", "Directory")',
data: {
searchTerm: value
},
cache: false,
success: function (result) {
//do something with your result,
//like replacing DOM elements
}
});
}
</script>
You also need to change the action that ajax will be calling (and I have no idea why you are calling the "Index" action).
public ActionResult Index(string searchTerm)
{
//lookup and do your filtering
//you have 2 options, return a partial view with your model
return PartialView(model);
//or return Json
return Json(model);
}
The best thing about this ajax is there is no posting and it's async, so you don't have to worry about losing your data.

Create a list with jquery and post it to asp.net mvc

I'm looking for a way to store the values of all existing checkboxes of a given class into some kind of list or array and send the result via jquery to an asp.net mvc controller. The checkboxes do not have to be checked, I need all of them.
More details:
My checkboxes look like this
<input type="checkbox" value="1" class="a-checkbox"
<input type="checkbox" value="2" class="a-checkbox"
<input type="checkbox" value="3" class="a-checkbox"
It would be nice if my MVC controller could look like this
public JsonResult SaveList(List<String> values) { //... }
I know that I could access the checkboxes in the following way
$('input.a-checkbox').each(
function () {
// create the list with the help of $(this).val()
}
);
// jquery post would happen here
But I dont know how to create such a data structure. Could you help me?
Thank you
edit: nice, thanks. Can you tell me whats wrong with this? My controller gets called indeed, but the list is null (on server side)
var list = [];
$('a-checkbox').each(
function () {
list.push($(this).val());
}
);
$.ajax({
type: "POST",
url: myUrl,
data: list,
success: function (data) {
alert(data.Result);
},
dataType: "json",
traditional: true
});
This will put all the checkbox values (value attributes) into an Array:
var values = [];
$(".a-checkbox").each(function () {
values.push($(this).val());
});
// values now equals ["1", "2", "3"]
Try this
var list = [];
$('input.a-checkbox').each(
function () {
// create the list with the help of $(this).val()
list.push($(this).val());
}
);
Now you can post list object to your mvc controller action.
I use .Serialize() to format form data for my mvc ajax actions.
var checkPostData = $(".a-checkbox").serialize();
http://api.jquery.com/serialize/
I had the same issue Nulls in my MVC mode and all. I found using $("input:checked") as my data instead of trying to extract the values to an array in js worked better and I fixed the Nulls issue by giving my checkboxes name values because MVC binds on input names.
HTML
<a class="post-checkboxes" href="#">post checkboxes</a>
<input name="[MVC viewmodel list variable name]" type="checkbox" value="1" />
<input name="[MVC viewmodel list variable name]" type="checkbox" value="2" />
Javascript
$('.post-checkboxes').click(function (e) {
e.preventDefault();
$.post("[location to post to]", $("input:checked"));
});

Categories