Tag Archives: AJAX

AJAX

pass model from View to Controller via AJAX – tried everything

Hello guys, 

I have tried everything trying to pass a model (from a strongly typed view) to a controller action using ajax and it always arrives empty, here is my code, please tell me what’s wrong with it (i have tried a variety of things tho and stll nothing has worked):

the model i am trying to pass is a ViewModel like this: (is the [Serializable] mandatory ?)

 [Serializable]
    public class RatingAreaViewModel
    {
        public int userId {get; set;}

        public double[] currentRating {get; set;}
        public double[] newUserRating { get; set; }

        public bool hasAlreadyVoted { get; set; }
        public double[] oldUserRating { get; set; }
        
        public int numberOfVotes { get; set; }

        public RatingAreaViewModel()
        {
            currentRating = new double[5] { 0, 0, 0, 0, 0 };
            newUserRating = new double[5] { 0, 0, 0, 0, 0 };
            oldUserRating = new double[5] { 0, 0, 0, 0, 0 };
        }

    }

and here is the ajax function in my view: 

  var obj = @Html.Raw(Model);
     
        function submitRating() {

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }
    

I have tried soo many combinations including JSON.Stringify and still the problem is that the model arrives empty at the controller (all zero values)

public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4)
{

    // AT THIS POINT HERE ALL VOTES ARRIVE OK BUT THE MODEL ARRIVES EMPTY
    
return partialview(...); }

thank you a lot guys!!

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Pass your data like this in jquery ajax call.

data: $(‘#formName’).serialize() + "&vote1=" + vote1+ "&vote2=" + vote2

Hi aymane07,

Based on my test, to serialize the object to JSON string, we should to use
JavaScriptSerializer
class.

For your requirement, you need add the object to a JSON, then convert it to the JSON string.

Please refer to this code below to achieve your requirement:

 public class Field
    {
        [Required]
        public string DataInfo { get; set; }

        [Required]
        public string Value { get; set; }

        //[MustBeTrue(ErrorMessage="required")]
        public bool IsRequired { get; set; }

        [Required]
        public int serverIDTo { get; set; }

    }
 public ActionResult JqueryFormSubmit()
        {
            Field f=new Field(){ DataInfo="dataInfor1", IsRequired=true, serverIDTo=2, Value="value1" };
            return View(f);
        }
        [HttpPost]
        public string JqueryFormSubmit(Field f, string txtQues,FormCollection c)
        {
            string str = txtQues ?? "empty";
            if (f != null && !string.IsNullOrEmpty(f.DataInfo))
                str += f.DataInfo;
            else
                str += " and null";
            return str;    
        }
@model MvcDemo2.Models.Field

@{
    ViewBag.Title = "JqueryFormSubmit";
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson=serializer.Serialize(Model);
}
 $(document).ready(function () {
            $('#btnSubmit').click(function () {
                var obj =JSON.parse('@Html.Raw(objJson)'); 
                var jsonData =JSON.parse(JSON.stringify({ f: {}, txtQues: "gg" }));
                //add object to json 
                jsonData.f = obj;
                 $.ajax({
                    url: '@Url.Action("JqueryFormSubmit")',
                    type: 'POST',
                    contentType:"application/json",
                    data: JSON.stringify(jsonData), 
                    success: function (data) {
                        //debugger;
                        alert(data);
                    },
                    error: function (response, xhr, data) {
                      }
                }
            )
            });
});

Best Regards

Starain Chen

What is this; formName ?? I think i don’t have any form in my View

Hello, 

I have tried your exact same code and it doesn’t work! all the votes are passed safely but the object is all zeros and falses :(:(:(

Is there something more basic i am missing…  here the code i tried exactly: 

[httppost] 
public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4) { }

function submitRating() {

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ f: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.f = obj;
            
            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


@{
    var url = Request.Url.AbsolutePath;
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson = serializer.Serialize(Model);   
}


Please tell me i am missing something i am getting really crazy here :(:(

thanks a lot

Hello

JohnLocke

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

Hello John, I have tried your code and it doesn’t work.. It doesn’t even compile at my end when I write this: 

var obj = @Html.Raw(Json.Encode(Model));

I have this error: IHTMLString returns markup that is not HTML…

cnuonline

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Hello, I have tried your code and it doesn’t work.. can’t even get to the controller this way.. plz help

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Starain chen – MSFT

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Thanks for your reply.. I have done exactly what you asked, and it still doesn’t work :)

I have noticed an issue with my code, when i use ravm: {} the request doesn’t even get to the controller action, whereas when i do
object:{} the request gets to the controller action but the object is all zeros. 

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

below is the working code that gets to the controller but with an emtpy project.. if you have anything else i can try please let me know.. 

thanks a lot!

function submitRating() {

            //var obj = 'Html.Raw(val)';

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ object: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));


            jsonData.object = obj;

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


I gave up for now and just passed an int Id instead of the object and reconstructed the object back in the controller: I did it this way: 

 $.post(url, { userId: id, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }, function (ratingAreaViewResult) {
                
                $('#ratingArea').html(ratingAreaViewResult);
            });

 BTW, when I pass only the object using this code, it works fine, but as soon as I add the integers the object fails to pass correctly:: there is some big elephant i am missing here!!

if you guys think of something please let me know::

thanks again

Hi aymane07,

aymane07

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

This code is used to generate the URL, the string of JqueryFormSubmit is just the action name. I am not using any form too.

aymane07

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

If you are just using JavaScriptSerialize, you don’t need add Serializable attribute to the model class.

Please use the developer tool to check the send data.

On the other hand, please share your project on the OneDrive, we will check it.

Best Regards

Starain Chen

[RESOLVED]AngularJS in ASP.NET MVC Partial View

I am currently loading Partial View returned by MVC controller to a model dialog via AngularJS $http.get call. My View in rendered properly in modal dialog, but the only problem is that my partial view which is rendered also uses angular expressions etc.
and for some reason angular is not working in my partial view, but if i load this partial view in some other view without ajax call then it angular works properly.

Partial View Code: ~/Views/ArticleType/_Add
MVC Controller: ArticleTypeController

//other scripts files e.g app.js and angular.js are included in main layout file.
<script src="~/Scripts/Angular/ArticleTypeController.js"></script>
<div class="modal-content" ng-controller="ArticleTypeController">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        Add New Article Type
    </div>
    <form novalidate role="form" name="ArticleTypeForm" ng-submit="ArticleTypeForm.$valid && Add(model)">
        <div class="modal-body">
            <div class="form-group">
                <label for="ArticleType" class="control-label">Article Type</label>
                <input type="text" required ng-model="model.ArticleTypeName" class="form-control" id="ArticleType" />
            </div>
        </div>
 
    </form>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" value="Add" >Add</button>
        {{ArticleTypeForm.$valid}}
    </div>
</div>

Angular Controller to load modal with the partial view.
MenuController.js

angular.module('myApp').controller('MenuController', [
        '$scope', '$http', 'httpPreConfig', function ($scope, $http, httpPreConfig) {
 
            $scope.AddArticleType = function () {
                $.get("/ArticleType/Add")//returns the partial view.
                    .success(function (response) {
                        ShowModal(response);//it properly shows the modal. but angular doesn't work
                    });
            }
        }]);

common.js 

$(document).ready(function (e) {
    
    $(document).ajaxStart(function (e) {
        $("#loadingBar").modal('show');
    });
    $(document).ajaxStop(function(e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxComplete(function (e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxError(function (e) {
        $("#loadingBar").modal('hide');
    });
});
 
function ShowModal(content) {
 
    //var html = $complie(content)(scope);
    $("#modal .modal-dialog").html(content);
    $("#modal").modal("show");
}
function HideModal() {
    $("#modal .modal-dialog").html("");
    $("#modal").modal("hide");
}

AS you can see from the image below that Angular expressions are not working in Modal Dialog. The html of this dialog is returned from MVC Controller whcih returns a partial view. 

Any help would be really appreciated. Just so that you know, angular expressions etc. are working in normal views.

Here is the download link to the solution files. : https://app.box.com/s/rxvrhwcdp75zo736k7u5

Hi asad,

According to your description, it works fine if you load that partial view directly, however it doesn’t work if using the AJAX to load the partial view.

I think you may need to compile HTML string or DOM into a template.

More information, please refer to:

# $compile

https://docs.angularjs.org/api/ng/service/$compile  

There are some threads that may help you:

# AngularJS – Dynamically creating elements that specify directives

http://stackoverflow.com/questions/20025526/angularjs-dynamically-creating-elements-that-specify-directives

# Bind Angularjs to newly created html element dynamically

http://stackoverflow.com/questions/19867554/bind-angularjs-to-newly-created-html-element-dynamically

Best Regards

Starain Chen

[RESOLVED]page and ajax

When the page
shows a portion of the content
using
ajax, it
has 2
connection -
to the current page
and the page
requested by ajax?
Likewise with the
iframe? Trying to
optimize your site, but it turns out
that the use of Ajax
only
clog the channel.

It initiates a new connection, but these connections are permanent, they only exist until the content is retrieved.  Use the network section of the browser’s developer tools (f12) and you’ll get to see all the connections your page makes.  It will make a
connection for each image, script file, css file etc too.  If any ajax code runs that will instantiate a connection, as will an Iframe, and any resources (images, script files, css files) used in the iframe will kick off a connection, as will any images etc
referenced by html you return from your ajax call.

[RESOLVED]How to chek why my website is long to be downloaded and what to do to decrease this time

Hi, i notice that my web site takes more time to be downloaded if i compare with other sites with same amounth of images…

How can i find what make my site long to be downloaded?

And how to fix?

Thanks

I believe the issue here is likely related to the physical sizes of your images, which can take quite some time to download if they are extremely large.

You’ll want to ensure that the image matches the size of the container you are intending to place it in and that the image has been optimized (to help reduce the size of it). When you see this occurring on a site, it is typically because the image
that is being loaded is :

  • The image(s) may be too large (for example a 800×800 image being loaded into a 100×100 container requires the browser to do lots of unnecessary work)
  • The image(s) are not optimized (you can use several online compressors like Smush.It or Kraken.io to optimize your images online)
  • The image(s) are physically quite large (this can depend on the types of files being uploaded, as files like bitmaps are extremely large).

Optimizing your images will likely help this issue tremendously. If you want to look at these requests, consider using the Developer Tools (F12) within Chrome and checking out the Network tab which will allow you to see each of your AJAX requests that are
made and their sizes.

Consider Using a Third-Party Analyzer

I would recommend running something an analyzer like one of the following on your site :

  • Using Google PageInsights - Google’s PageInsights can help you find areas of improvement and offers suggestions on how to get your site running faster.
  • Using Yahoo’s YSlow Analyzer - Very similar to Google’s PageInsights, YSlow looks for areas that you can check to improve the performance of your site.

It will provide you with any major concerns that might be slowing down performance on your site and how to resolve these issues. You might see something like the following after running it, which will let you know what images you need to consider optimizing
and the amount of size that you will save :

One Final Recommendation

If you want an excellent resource that encompasses a variety of methods to improve your website or web application, I cannot recommend the Web Developer Checklist enough. There
is also an ASP.NET-specific version available on the site as well
 and one that focuses specifically on ASP.NET Performance. It’s probably one of the best single resources that I have found for
improving nearly all aspects of a website or web application.

[RESOLVED]Layout Needs a Model

Hi All,

I am working on a project for which the UI was created by someone else.  The project has a Partial View called _ApplicationLayout.cshtml that renders on every view page in the project.   It also hosts several partial views, one of which is the "_Comments.cshtml"
view in which I need to display all of the comments from the database that are associated with the application in the right bar of the layout.  I cannot use a View Model in the _Comments.cshtml partial, because it is rendered in the _ApplicationLayout.cshtml
and of course the View Model clashes with all of the other View Models throughout the project.  Can anyone tell me just how can solve this problem?  The comments do need to show on every page (view) in the project.

You can do it via two different ways,

  1. Call @Html.RenderAction  rather than partial to render the result of an action method, that will give you chance to separate out the code with strongly typed model
  2. Create a base controller and initialize the data and assign it to ViewBag which is required for comments view, now all controllers will inherit from base controller and they will have the data available.

I would prefer the first approach as it is a MVC way of doing things and avoid any accidental miss of controller inheritance.

Either move the comments-partial to the actual View, or replace the Partial helper with an Action helper and pass it an ID/value to process data and return a partial view

Example–

Instead of:

@Html.Partial("_Comments")

do:

@Html.Action("GetComments", new { id = X })

where X could be a ViewBag.Value or a URL parameter, example:

@Html.Action("GetComments", new { id = ViewBag.BlogID })

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(c => c.BlogID == id).ToList();

  return PartialView("_Comments", comments);
}

The problem is that there  will be a list of comments, and there is a "textarea" for adding more comments on the fly.  Will the solution you suggested still work?  I don’t have the option of moving the Partial out of the _ApplicationLayout.cshtml.  Also,
how can I specify the controller where the ActionResult is in the code:

@Html.Action("GetComments"new { id = ViewBag.loanApplicationId})
?

You can specify the Controller as another parameter of the Action helper:

@Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })

As for your text-area, just give this input a name that matches the post-action param:

@using Html.BeginForm("AddNewComment"))
{
@Html.Hidden("ApplicationId", ViewBag.loanApplicationId)
<div>
Add Comment: @Html.TextArea("NewComment")
</div>

<input type="submit" value="Submit" />
}

Action:

[HttpPost]
public ActionResult AddNewComment(int ApplicationId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

return redirectToAction("Index"); }

That’s a fairly simple solution.  If you have questions, ask away

Okay, I think I understand it now.  The only other question I have is if they should add a comment (remember they could be on any View page in the project), Once the comments pane is updated the user is has to return to the same view.  From what I have read
online, this should be some sort of "child action only".  Is that correct?

By the way, you are really awesome to have taken the time to help me!  I wish I could send you a gift!

So what you want to do is use an Ajax form, process the comment, then return a fresh instance of your Partial view back to the main View.  Let’s go through the whole thing, but with the ajax:

1) In your _Layout, you’ve got the Html.Action(…) helper.  We should wrap this in a <div> tag because we’re going to update this after our ajax-post

<div id="commentsDiv">
  @Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })
</div>

2) In your partial view, you’ve got your form that allows the user to add a comment.  We’re going to change this to an Ajax form

@using (Ajax.BeginForm("AddNewComment", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppId", ViewBag.loanApplicationId)
  <div>
    Add Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

3) In the post-action, we process the new comment, then return our *UPDATED* _Comments partial view back to the view

[HttpPost]
public ActionResult AddNewComment(int AppId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

var comments = db.Comments.Where(c => c.ApplicationId == AppId).ToList();

return PartialView("_Comments", comments); }

And that’s it!  Now it’s important to note that you MUST have the unobtrusive-ajax scripts included in your View.  If you are unsure whether you have these, check your Scripts folder (download them from the NuGet manager if needed).

I received the following error when I tried to run this:

"Additional information: Error executing child request for handler ‘System.Web.Mvc.HttpHandlerUtil"

I tried to run in without the Id in the parameters and just hardcoded the ID in the method just for testing.  Here is what is in my _ApplicationLayout:

  <div id="PageClassDiv" class="@(ViewBag.PageClass) APPLICATION"><!-- page content container-->
        
        @Html.Partial("~/Views/Shared/_NavigationView.cshtml") <!-- Navigation Partial View -->
        @Html.Partial("~/Views/Shared/_SearchAccordionView.cshtml") <!-- Search Accordion Partial View -->

        <!-- All applications should have comments and sidebar ============================================================================================-->
        @Html.Partial("~/Views/Shared/_SideBarView.cshtml");
        @*@Html.Partial("~/Views/Shared/_CommentsView.cshtml");*@
        @Html.Action("GetComments", "LoanApplication")
        
        <!-- content ============================================================================================-->
        @if (angularEnabled)
        {
            <div class="container" ng-app="@angularAppName">@RenderBody()</div>
        }
        else
        {
            <div class="container">@RenderBody()</div>
        }
    </div><!-- end page content container-->

This is the CommentsView:

<span class="comments">
    <a id="right-menu" href="#right-menu" class="icon-comments"></a>
</span>
<span class="clear"></span>

<div id="sidr-right" class="sidr right">
    <header>
        <h4> Application Notes </h4>
        <a href="#" class="icon-print"></a>
        @using (@Html.BeginForm("Comment", "LoanApplication"))
        {
           @Html.TextArea("Comment")
        @*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*@
            <input value="Add Comment" type="submit" />
        }
    </header>

And this is what is in my controller:

  [HttpGet]
        [Route("GetComments")]
        public async Task<ActionResult> GetComments()
        {
            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;

            var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();
            
            return PartialView("_CommentsView", comments);
        }


 [HttpPost]
        [Route("Comment")]
        public async Task<ActionResult> Comment(FormCollection form)
        {

            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
            var userId = this.User.Identity.GetUserId();
            string comment = Request.Form["Comment"];
            var applicationComment = new LoanApplicationComment
            {
                Comment = comment,
                CreatedDate = DateTime.Now,
                LoanApplicationId = loanApplicationId,
                Id = Guid.NewGuid(),
                CreatedBy = Guid.Parse(userId)
            };
            await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);

            var comments = loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId);

            return View(comments);
         
        }

The code in the Controller "GetComments" never gets hit.  The application throws an error as soon as I try to navigate to a View page that has the comments pane.

BeeDev

The code in the Controller "GetComments" never gets hit.

take off the [HttpGet] and [Route("GetComments")] annotations, and see if that works.

I was able to get it to hit the controller, but I can’t figure out how to actually display the comments.  I’m used to using @model.Comment, or something of the sort, but there is not model, so how do I specify the fields that I need to display?  I must display
the user name, date and time of comment, along with the comment.

This is going beyond the original scope of the question.  If I understand everything correctly, your _Comments partial view displays rows of comments that include user name, date & time of comment, and the comment.

The model for Comment may look something like this (I’m just guessing since you have not posted the actual model):

public class Comment
{
public int CommentId { get; set; } public string Comment { get; set; }
public string UserName { get; set; } public string CDate { get; set; }
public int App_ID { get; set; } }

The model includes a primary index key (CommentId), the other required fields, and also a foreign key reference (App_ID)

The _Comment partial view may then look like this:

@model IEnumerable<AppName.Models.Comment>

<h2>Submit Comment</h2>

@using (Ajax.BeginForm("AddNewComment", "LoanApplication", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppID", ViewBag.loanApplicationId)
  <div>
    Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

<h2>Comments</h2>

@foreach (var item in Model)
{
  <div>
    <dl class="dl-horizontal">
      <dt>Username</dt>
      <dd>@Html.DisplayFor(modelItem => item.UserName)</dd>

      <dt>Date</dt>
      <dd>@Html.DisplayFor(modelItem => item.CDate)</dd>

      <dt>Comment</dt>
      <dd>@Html.DisplayFor(modelItem => item.Comment)</dd>
    </dl>
  </div>
}

To explain, our @model is a LIST of comments that will be passed to the partial view.  At the top I’ve included the AJAX form, which allows a user to submit their comment.  Below the form is the Comments section, which loops through each comment, displaying
the User, the Date, and the Comment (I used DL formatting but you can use TABLE or DIV, etc).  Now when the form posts and finishes processing, we’ll be returning a fresh _Comments partial view, which will replace the old one.  We use "UpdateTargetId" to specify
where to update.

Your AJAX post-action in your "LoanApplication" controller:

[HttpPost]
public ActionResult AddNewComment(int AppID, string NewComment)
{
  // create new comment object
  var comment = new Comment();
  comment.Comment = NewComment;
  comment.UserName = User.Identity.Name;
  comment.CDate = DateTime.Now;
  comment.App_ID = AppID;

  // add comment to db
  db.Comments.Add(comment);
  db.SaveChanges();

// query new comments list and return to partial view var comments = db.Comments.Where(c => c.App_ID == AppID).ToList(); return PartialView("_Comments", comments); }

I’ve commented this for explanation.

Your _Layout view now only needs to have the initial Action helper inside a named DIV

<div id="commentsDiv">
  @Html.Action("GetComments", "LoanApplication", new { id = ViewBag.loanApplicationId })
</div>

As said earlier, once the AJAX form posts, a new version of _Comments partial view will replace the contents of "commentsDiv".

Lastly, the "GetComments" action (in the LoanApplication controller):

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(App_ID == id).ToList();

  return PartialView("_Comments", comments);
}

And that’s it.  There’s the entire solution…  If all of this works for you, please take a moment to mark all my responses as answers, as they all answer each of your subsequent questions.  Thanks.

Okay, I figured out that I can put a model in the _CommentsView.cshtml since it is being rendered with an @Html.Action.  Thanks for ALL of your help!  You are awesome!!!

[RESOLVED]Convert ajax call into chunked calls of 100 for a URL

Excuse me here, I’m rather new to this, so please bear with me.

I have been given the task as stated in the subject, to break the ajax call into chunks of 100.  This is being done as to not run out of URL space.  My instinct (which is probably wrong) is to pass it through as an array.  This is where I’m hitting a wall.
 Here is a chunk of code in the index of Views.

$(document).ready(function() {
var imageNos = ‘@Model.ImageNos’;
var array = imageNos.split(‘,’);

var oTable = $(‘#imageTable’).dataTable(
{
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "ImageData/GetList",
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bJQueryUI": true,
"aoColumns": [
{ "bSortable": false, "bSearchable": false },
null,
null,
null,
null,
null,
null,
null
],
"fnServerData": function(sSource, aoData, fnCallback) {
aoData.push({ "name": "ImageNos", "value": array });
$.getJSON(sSource, aoData, function(json) {
fnCallback(json)
});
},
"fnRowCallback":function(nRow, aaData) {
var imageno = aaData[1];
$.get("ImageData/ImageDetails?imageNo=" + imageno, function (details) {
oTable.fnOpen(nRow, details, ‘details’);
});
return nRow;
}
});

here is how I;m trying to pass it through to the controller.

public ActionResult GetList(string[] value)
{
var imageNos = new List<long>();
try
{
if (!string.IsNullOrEmpty(value))
{
/*var imgs = ImageNos.TrimEnd(‘,’).Split(‘,’).ToList();
imageNos.AddRange(imgs.Select(i => Convert.ToInt64(i)));*/
}

long totalImages;
var images = ImageRepository.GetSelectedImages(imageNos);
var imageDataModels = images as IList<ImageDataModel> ?? images.ToList();
return Json(new
{
iTotalRecords = imageDataModels.Count,
iTotalDisplayRecords = imageDataModels.Count,
aaData = imageDataModels.Select(x => new[]
{…………

As it is now, I’m getting errors

Error 1 The best overloaded method match for ‘string.IsNullOrEmpty(string)’ has some invalid arguments and 

Error 2 Argument 1: cannot convert from ‘string[]’ to ‘string’ 

I know this is a lot of code, and i’m not even sure I have posted anything that could help someone assist me, but any help on this would be greatly appreciated; I’m feeling a bit overwhelmed and underwater.

edit: I meant to say beforehand that everything works fine before I try the array above, before I split it in the index

I can’t really follow what the code is doing, but you’re getting that error as

string.IsNullOrEmpty(value)

in the above "value" is an array, and IsNullOrEmpty works on strings, not arrays of strings.  If you want to check if an array isn’t empty try

if (value != null && value.Length >0)

Not saying that’s going to fix your issue, but it will get your code to compiled.  Also if you’re worried about "running out of url space" then just POST your data rather than using GET and you don’t need to worry.

Getting data of json array

I create an array with javascript that has some ids. I pass them back to my controller like so

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

What I’m not sure on is how I get that data in my c# code to work with it. Here’s my function in my controller

//how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(object var)
        {
            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

The param you choose for your ‘data’ option in the ajax-request must match the param of your post-action. 

[HttpGet]
public JsonResult GetChildKeys(someType ids)
{
...

Is nodeKeys a list of objects, or a string?  That will determine the "someType" above

I knew I’d have to get the type, I just wasn’t for sure what type it would be.

nodeKeys is just a javascript string array;

Something like 

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

That’s not json, but anyway, try

string[] ids

or

List<string> ids

Then you could do

[HttpGet]
public JsonResult GetChildKeys(string[] ids)
{
foreach (var id in ids)
{
// process each id here
}

...
}

I was under the impression if I sent the data like this (underlined in bold)

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

that it would convert that to json for me?

The "data" node will be json, but the data you are passing in the "ids" property is just a plain javascript array.

hi,

usually ajax communication more serialized content, while receiving  action method have to serialise as per mention data type, 

client : var array1 = ["A", "B", "C", "D"];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code…… }

client : var array = [1, 2, 3, 4, 5];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code….. }

or just pass json string, then in controller action have to parse posted json to respective model object.

Ref : serializing and deserializing json in c#

Thanks,

Jai

So how do I go about passing that array back to my application?

Basically, there’s some code that runs through a treeview and pulls the ids of any checked items and pushes them into the array. So, I need to send that array of ids back to my controller as json data. I don’t really care how they get there, array, list,
etc. but I just need to be able to loop through them. Ideas?

hi,

Client :

var selectedItems = [1, 2, 3, 4, 5]; // try to push your selected item.

$.ajax({
url: "/Account/AjaxCallTest/", //your url
traditional: true,
dataType: "json",
type:’post’,
data: { ids : selectedItems },
success:function(data) { 
},
error: function (errorMsg) {
}
});

Server:

[HttpPost]
public JsonResult AjaxCallTest(List<int> ids )
{
// your logic…
}

Thanks,

Jai.

That’s what I tried after your first post with no luck. This is what I have

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

C# 

        //how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(List<string> ids)
        {
            //ids is still null
            var foo = ids;

            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods

either add

contentType:
"application/x-www-form-urlencoded; charset=UTF-8",

to your $.ajax call, or try

data: JSON.stringify({ ids: nodeKeys }),

I’ve tried both of those and ids is still null

nodeKeys = ["cat_1", "cat_2", "cat_3"];
$.ajax(
{
url: "/Home/GetChildKeys",
data: JSON.stringify({ ids: nodeKeys }),
dataType: "json",
type: "GET"
}).done(function (result) { });

and even

nodeString = "cat_1,cat_2,cat_3";
$.ajax(
{
url: "/Home/GetChildKeys",
data: "{keys: ‘" + nodeString + "’}",
dataType: "json",
type: "GET"
}).done(function (result) { });

You have to set the correct contentType too so the service knows how to interpret the data you are sending.  As well as the link I posted with all the examples, look at this to see how you can use the browser’s dev tools to see what is being sent and what
the response is.

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+

[RESOLVED]Unable to get updated cookie value in jquery after ajax call

I have made a simple cart example in mvc. what I’m doing is , after clicking on Add to cart span , I’m calling a Controller Action method.

And then updating the cookie value with Total no of item in cart. but it give me initial value of cookie.

This is my Ajax Code to call Controller Action

$(document).delegate('.addCart','click', function () {
            var getId = parseInt($(this).attr('id').slice(3));
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Comments/CartDetailsSetGet',
                data: { Id: getId },
                success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;
                        $('.cartNum').html(getCookies);
                    }
                },
                error: function (data) {
                    alert("Error In Adding Item To Cart");
                }
            });
        });

There is span > with class cartNum in which I’m showing Total no of item in cart .

addCart is span on which I’m Clicking to Add Item In Cart.

This is my Action Method , which is My default Action

GuestbookContext db = new GuestbookContext(); // my DbContxt Class
        HttpCookie ck = new HttpCookie("CartCookie");
        public ActionResult Index()
        {
            if (Request.Cookies["CartCookie"] == null)
            {
                ck.Value = "0";
                Response.SetCookie(ck);
            }
            IList<Comment> commentList = db.Comments.ToList();
            return View(commentList);
        }

This Action Which is getting called On Ajax Request.

static List<int?> CartItemsId = new List<int?>();
        public string CartDetailsSetGet(int? Id)
        {
              if (CartItemsId.Contains(Id) != true)
                {
                    CartItemsId.Add(Id);
                    int getCount = CartItemsId.Count();
                    System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value = getCount.ToString();
                    ck.Expires = DateTime.Now.AddDays(-1);
                    var d = "";
                    if (System.Web.HttpContext.Current.Request.Cookies["CartCookie"] != null)
                    {
                        d = System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value;
                    }
                    return d.ToString();
                }
                else
                {
                    return "This Item Is Already In Cart";
                }
            
        }

Here in d I’m getting updated cookie value but in Ajax Success , this line giving me Initial value, i.e 0.

var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;

Your razor code is server-side code, it isn’t running inside the browser.  View the source of your page and you’ll see

success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  0;
                        $('.cartNum').html(getCookies);
                    }
                },

so no matter what happens, getCookies is always going to be 0.  You need to read the data from the document.cookie object

http://www.w3schools.com/js/js_cookies.asp

or return the data as part of your ajax method (either as well as, or instead of the cookie)

return View(new {Comments: commentList, Quantity: ck.Value);

then amend your success code to reflect this change