I want to send a complex object from my view (via Ajax) to my controller. I know that I can do something like:
JSON.stringify(myComplexObject);
and then retrieve values in the controller. But is this really the best way to do it? I'm thinking some sort of data contract between view and controller would be better?
you can use the following
#using(Html.BeginForm("YourAction","YourController",FormMethod.Post))
{
....
}
<script>
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert('Ok');
}
});
}
return false;
});
});
</script>
and in your Controller
public ActionResult YourAction(YourModel model)
{
}
hope this will help you
Related
I have the following code:
<script type="text/javascript">
$('#btnConfirmAddition').click(function () {
var contractorId = $("#contractorId").val();
var contactPerson = $("#addNewContactPersonForm").serialize();
$.ajax({
url: '#Url.Action("AddContactPerson", "Contractors")',
type: "GET",
data: { newContactPerson: contactPerson, contractorId: contractorId },
//data: contactPerson,
success: function (data) {
$("#myModal").modal('hide');
toastr.success("Success");
location.reload();
},
error: function (data) {
$("#errorArea").html(showError(data.ErrorMessage));
toastr.error(data.errorMessage);
}
});
return false;
});
</script>
public JsonResult AddContactPerson(ContactPerson newContactPerson, string contractorId)
{
//Some code
}
When I pass parameters in ajax call as above, my newContactPerson is null and contractorId contains appropriate data.
However when remove contractorId parameter from controller's action and pass parameter in ajax call as follows:
data: contactPerson
it works. I was wondering why? Can someone please help me?
post your data following way,
data: $("#addNewContactPersonForm").serialize() + '&contractorId='+ contractorId
And add data type to Ajax call,
dataType: "json"
I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method
I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me
The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?
Assume that I have a public function in IndexController called test():
public function test(){
//some code here
}
In index.phtml view file, I want to use JQUERY AJAX to call test() function but have no idea about this.
Code:
Click me to call test() function()
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: ***//WHAT SHOULD BE HERE***
Success: function(result){
alert('Success');
}
});
}
</script>
I would suggest writing an action for it. If there is logic inside of test() that you need other actions to be able to use, the factor that out.
There are a couple of reasons for having it be its own action:
You can test the results of the action directly instead of having to go through a proxy.
You can take advantage of context switching depending on if you need JSON returned or HTML
It is an action that you are trying to hit via AJAX, so there's no need to hide it.
Remember that not every action has to be its own full fledged page. One thing to make sure you do is disabling the auto-rendering of the view inside this action so it doesn't complain about not being able to find it.
public function ajaxproxyAction(){
if (is_callable($_REQUEST['function_name'])) {
return call_user_func_array($_REQUEST['function_name'], $_REQUEST['function_params'])
}
}
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: '/controller/ajaxproxy/',
data: { function_name: 'echo', function_params: 'test' }
Success: function(result){
alert('Success');
}
});
}
</script>
public function ajaxproxy2Action(){
if (method_exists($this, $_REQUEST['function_name'])) {
$retval = call_user_func_array(array($this, $_REQUEST['function_name']), $_REQUEST['function_params']);
echo json_encode(array('function_name' => $_REQUEST['function_name'], 'retval' => $retval));
die;
}
}
just think about this way ;)