access the variable in my javascript from controller - asp.net-mvc

In my CSHTML I have some JavaScript which contains a string variable. How do I access this variable from my controller?

When you invoke the controller you could pass it as parameter. For example if you are invoking the controller action using AJAX:
$.post('/someaction', { someValue: someVariable }, function() {
...
});

[HttpPost]
public ActionResult someAction(string id)
{
return Content("got it");
}
in script
$(function(){
var someid='12';
$.post('/Controller/someAction',{id:someid},function(data){
//this call back is executed upon successfull POST
console.log(data); // got it"
});
});

You can use a hidden input field in your form valorized with the value of your string variable. When you post the form you can read the value as usual.

Related

Listing Products List when clicking the checkbox which comes from Database

My question is about listing product list. I have a category list I've created with checkbox.
When clicking the checkbox, the product list must be listed according checkbox.
I tried to do with json and ajax,but I didn't manage to do.
Are there are any ideas ?
example
Do you mean passing values from the cheeckbox in the View to the controller?
You can use Ajax for this;
insert the checkboxes in a form element and set the Id attribute of the form
something like "FormId";
function Submit() {
$.ajax({
url: "/Home/Index",
type: "POST",
data: $("#FormId").serialize(),
success: function (result) {
if (result.Durum == "OK") {
$('#FormId').html("Successful");
}
And the html;
<form id="FormId">
<input id="checkBox" type="checkbox" name="Data">
<button onclick="Submit()"> Submit</button>
</form>
In the controller;
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index(var Data)
{
//your code here
return Json("OK", JsonRequestBehavior.AllowGet);
}
Notify the name attribute in the checkbox has the same value in the controller Index method's input parameter. You can pass variety of data regardless of data types, with serialize method of Ajax to the method in the controller, it will catch the right data as long as the name attribute and the input of the Index method have the same value.
If you want to pass only single data, just get the value of the certain form element with .val in the js code;
function Submit() {
$.ajax({
url: "/Home/Index",
type: "POST",
data: $("checkBox").val(),
success: function (result) {
if (result == "OK") {
$('#FormId').html("Successful");
}
And also notify the POST type in the ajax function, this means you should put [HttpPost] attribute to the Index method in the controller. In the screenshots you shared, you call the ajax method with GET method but in the controller you receive it with the [HttpPost] attribute, this wont work.

OnClick event on different things like divs, img and so on then use data from those in controller to do something

I been googling for about two hours and couldn't find anything about it.
What does one use(frameowork or maybe it is already uilt up in mvc) to pass data from VIEW to controller.
For example lets say I have a list of products and I wanna delete it without refreshing a page just by clicking on the thing like <div data="23020id" onclick="doSomething()"></div> and so if I would press on that div, something would happen in controller without refreshing the page.
I don't know how to google it or what should I've been aiming for here.
I've seen that many websites does it but I don't really know what they use and how they do it.
Could someone give me any direction?
Let's start with your example.
lets say I have a list of products and I wanna delete it without
refreshing a page just by clicking on the thing like
<div data="23020id" onclick="doSomething()"></div>
Here it simply means you're calling javascript function doSomething() on click. But you can give Id to that div and perform click on that id.
<div id="test"data="23020id"></div>
Now what could be in the this function?
This function called your controller method via an ajax call, which will send Id to the controller which we need to delete.
javascript code:
$('#test').click(function() {
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:id},
success: function(data) {
// update some DOM element with the result returned by the
// server. So supposing that you have some <div id="someContainer">
// that will contain the part of the DOM you want updated:
},
error: function() {
alert("error");
}
});
});
Now when you click on button, that will call your controller method and pass id.
public ActionResult Delete(int Id)
{
// do delete here.
return Json(data);
}
Perform deletion on method and return view, and update it on ajax success.
I suggest you to use Partial View for such things. For more see here: Rendering a Partial View and JSON Data Using AJAX in ASP.NET MVC
you can try with this
you can not return View() from ajax call. you need to retrun Json()
you Action method
public ActionResult Delete(int Id)
{
// delete method call
return Json("success", JsonRequestBehavior.AllowGet);
}
your ajax call
$("#divId").click(function() {
var dataattr = $(this).attr("data"); //use this variable
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:dataattr },
success: function(data) {
refresh your DOM element
},
error: function() {
alert("error");
}
});
});
you could use JQuery for that..
$("#divId").click(function() {
dataattr = $(this).attr("data"); //use this variable
$(this).hide();
});

how to pass data from View to Controller using ajax get or post in mvc with parameters

I am trying to pass data from View to Controller Action Method using ajax as follows:-
I have Membership instance of user which I passed in from another controller to this view below using viewbag somewhat like this ViewBag.MyUser = MyUser;
Now I want to pass 'MyUser' to another Controller form this view using ajax as below.
$('#Link').click(function () {
$.ajax({
url: http://localhost/Account/Process,
type: 'POST',
data: '#ViewBag.MyUser',
success: function () {
},
error: function () {
}
});
The ActionMethod to which I am posting is as follows
public ActionResult Process(MembershipUser MyUser)
{
//Do somethihng with MyUser
}
If I pass do ajax post, I get error internally at BeginExecuteCore(AsyncCallback callback, object state) stating that 'No parameterless constructor defined for this object.' and control does not even comes to my actionmethod.
If I remove the parameter (MembershipUser MyUser) from Action Method it posts to Action method, but then
how can i pass 'MyUser' in such case without parameter from that view to controller ?
is there something wrong with routes ? if yes what should be the route ?
or should i use get or post ?
Where should i cast the MyUser back to MembershipUser ?
The problem is you can't pass MyUser as parameter from JQuery because JQuery doesn't know the class MembershipUser. Remember that JQuery is a client side language and MembershipUser is defined in C# on the server side.
You could pass the properties that you need from the MyUser object to the Process action using GET as follows (supossing that the MyUser object has and ID an a Name):
$('#Link').click(function () {
$.ajax({
url: http://localhost/Account/Process,
type: 'GET',
data: {
id: "#ViewBag.MyUser.ID",
name: "#ViewBag.MyUser.Name"
},
success: function () {
},
error: function () {
}
});
The action should be something like this:
public ActionResult Process(int id, string name)
{
//Do something
}
I hope it helps you!

jQuery post to another controller

If I have a Controller called "HomeController" and I'm on the Index page of that controller, how can I do a jQuery Ajax post to another controller.
I tried the below,
$.post("/DetailedQuote/jQueryGetDetailedQuote", { productCode: "LPJ" }, function(newHTML) {
alert(88);
});
I have a DetailedQuoteController.
I have also tried;
post("DetailedQuote/
post("DetailedQuote.aspx/
post("/DetailedQuote.aspx/
post("/DetailedQuoteController/
post("DetailedQuoteController/
post("DetailedQuoteController.aspx/
post("/DetailedQuoteController.aspx/
And still no joy.
I should also mention that this is running a Hybrid WebForms and MVC site on IIS 6.
EDIT
The error that is being returned in error: is "error" so I assume that's maybe a 404.
In fact, it is a 404. I just checked.
This should work:
public class DetailedQuoteController : Controller
{
[HttpPost]
public ActionResult GetDetailedQuote(string productCode)
{
return Json(new { Code = productCode, Quote = 123 });
}
}
And to invoke it first declare a global javascript variable containing the address of this controller somewhere inside the view:
var quoteAddress = '<%= Url.RouteUrl(new { controller = "DetailedQuote", action = "GetDetailedQuote" }) %>';
And finally call the method:
$(function() {
$.post(quoteAddress, { productCode: 'LPJ' }, function(json) {
alert(json.Quote);
});
});
There doesn't appear to be anything wrong with your jQuery command, so the most obvious place to start looking is in the controller itself. Things to check would be:
Does your Controller action return a Json response (e.g. public JsonResult jQueryGetDetailedQuote)?
Are you using the Json() method to return your object?
Do you have your action decorated with the [HttpPost] attribute?
Perhaps you could post part of your controller code as well?
I notice that in your jQuery method you're calling an action called jQueryGetDetailedQuote. If your intention is purely to just GET a result, then perhaps you should use jQuery's $.get() or $.getJSON() functions instead?

How to send a model in jQuery $.ajax() post request to MVC controller method

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("#Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
Article on MVC JSON deserialization
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
#model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '#Model.TestId',
CreatedDate: '#Model.CreatedDate.ToShortDateString()',
TestDescription: '#Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '#Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'#Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
I think you need to explicitly pass the data attribute. One way to do this is to use the
data = $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize
you can create a variable and send to ajax.
var m = { "Value": #Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
In ajax call mention-
data:MakeModel(),
use the below function to bind data to model
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
on POST this data will get available

Resources