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

How can I use async in Application_Error() in Global.asax.cs?

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Maybe that is not modified . Use .Result for task – or, if you want  all to finish, Task.WaitAll

jakubarnold

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Hi jakubarnold,

Thanks for your post.

What I understand from you is that you want to write mvc application exception message to remote server asynchronously.

For this issue, you should mark the Application_Error as async like below:

protected async void Application_Error(object sender, EventArgs e) 
        {
            Exception ex = Server.GetLastError();
            var isSuccess=await MethodAsync(ex);
        
        }
async Task<bool> MethodAsync(Exception ex)
        {
            //your code write exception to remote server.
            //...............

            return true;
        }

Thanks.

Best Regards!

The HTTP pipeline has APIs to register for async versions of all the methods you see in global.asax. You can then incorporate that with Tasks. This might help:

http://brockallen.com/2013/07/27/implementing-async-http-modules-in-asp-net-using-tpls-task-api/

Is your intention is to return the page back to the user while logging the error? Typically this makes sense as you don’t want to block user while logging errors. Async does not support this behavior. It will still be a synchronous call to your user. Please
check the below blog for more details

Async Doesn’t Change the HTTP Protocol

If your intension is not to hold up the web server thread while doing the error logging, I recommend using async HttpModules for this.

Implementing async HTTP modules in ASP.NET using TPL’s Task API

[RESOLVED]MVC file storage best practices

Hey guys, I just wanted some quick feedback as this is my first time dealing with file storage and I’d like to do it properly.

I’ve got public downloads. They are available if under the right role. My plan was to store them in a database. Have a back end where the client can update existing downloads. (We usually have monthly new version releases). The size of all the files can’t
be more than 2GB.

I’ve read that storing files on the web server can be a security risk, and that I should have a separate service for file serving. This seems like a bit of overkill for what I need.

I’m not looking for instructions on how to store on a database, I’ve got that figured out. Just want to make sure I’m approaching this the right way. Could be overthinking it as well.

Thanks.

adam3039

Could be overthinking it as well.

Of course. Anyway, SqlServer have FileStream column

http://technet.microsoft.com/en-us/library/bb933993(v=sql.105).aspx

Hi adam,

For this requirement, you also could consider using the FTP to manage files. You could have a server that used to storage files, then configure a FTP site in the IIS.

After that you could upload the files to the FTP server.

# How to: Upload Files with FTP

http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx

Best Regards

Starain Chen

adam3039

I’ve read that storing files on the web server can be a security risk

As per your description, you are storing the files in the database and not in the web server. Is this correct? In that case you are already using database service for file serving :)

As web servers are outside the firewalls they more vulnerable for attacks. Hence people recommend to put the files inside the firewall and use some kind of service to deliver the files. In your scenario you can have your database inside the firewall and
deliver the files to the webserver. 

[RESOLVED]problem with show data in view

Hi

I use ckeditor for send new post and ( code snippet  plugin ) , when I send new post and return to see post i can’t  see code snippet >>

view >>

Help me to show best data . .  I want when read data from controller show code with default ( Picture >> 1 << ) 

omid.nasri

I want when read data from controller show code with default ( Picture >> 1 << ) 

PLease explain better. I did not understand your question – nor the picture.

Mr
ignatandrei

I read data from Controller ( public actionresult index() ) with foreach key Ok! >>

public actionresult index()

{

var Q = (from t in mvc.tbl_test where t.id == 1 select t).tolist();

return view(Q);

}

now : I have problem with show data , I want when read data if user use  ( code snippet plugin in ckeditor ) show like  ( default in pictures ).

helpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp

Hi omid.nasri,

Thanks for your post.

According to your description,

omid.nasri

I want when read data if user use  ( code snippet plugin in ckeditor ) show like  ( default in pictures ).

You can to implement insert code snippet functionality?like this:

If so ,you can refer to this:

#Insert code snippet in CKeditor

http://www.ingeniumweb.com/blog/post/insert-code-snippet-in-ckeditor/1213/

Hope this can be helpful.

Best Regards,

Eileen

Try removing the Html.Raw and see you are able to see the code. Also check the View Source to see that your code is in the source and not showing in the display.

[RESOLVED]Browser Info in MVC

Hi,

I need to capture the browsers info and count no. of requests coming from the browser.

and also i need to block the request , if the request comes from a specified browser say FireFox

Depending on these requests and their count, i need to generate a report or a chart in dashboard.

Thanks,

Vijay 

The browser info in in the agent string header. Here is site that keeps track of the current agent strings. New ones appear with every new phone.

http://www.useragentstring.com/pages/useragentstring.php

You get the agent string with Request.UserAgent.

For hit tracking you process your web logs, or use google analytics.

You can use a MVC filter or constraint to handle your scenario. Please check these links

Filter actions based on UserAgent

ASP.NET MVC: Custom Constraints – Matching the User Agent String

vijayd48

Depending on these requests and their count, i need to generate a report or a chart in dashboard

It would be better if you can use some analytic services such as google analytics for this.

[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]LINQ to Entities, selecting mutiple columns to already declared model getting anonymous type error.

I am trying to fill my `ViewModel` from a few different LINQ queries but I am running into the problem of trying to fill multiple properties from a single LINQ query but I get the error

"invalid anonymous type member declarator. anonymous type members must be declared with a member assignment, simple name or member access"

I have done some searches and founds some posts but they are all about completely filling a `ViewModel` and not just a few properties like I am trying to do. What am I supposed to do to fix this, or am I going about this completely wrong?

using (ForumContext db = new ForumContext())
{
	model.ID = db.yaf_Topic
				.Where(t => t.ForumID == 5)
				.OrderByDescending(t => t.Posted)
				.Select(t => t.PollID.Value).First();

	model = db.yaf_Poll
				.Where(p => p.PollID == model.ID)
				.Select(p => new
				{
					model.Question = p.Question,
					model.IsMultipleChocie = p.AllowMultipleChoices,
					model.ExperationDate = p.Closes
				})
				.First();

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select(c => new
						{
							model.Votes.Key = c.Choice,
							model.Votes.Value = c.Votes,
						})
						.ToList();

	model.VotedIPs = db.yaf_PollVote
						.Where(p => p.PollID == model.ID)
						.Select(p => p.RemoteIP)
						.ToList();

	model.VotedUserIDs = db.yaf_PollVote
							.Where(p => p.PollID == model.ID)
							.Select(p => p.UserID)
							.ToList();
}

ViewModel:

public class PollVM
{
	public int ID { get; set; }
	public string Question { get; set; }
	public bool IsMultipleChocie { get; set; }
	public DateTime? ExperationDate { get; set; }
	public KeyValuePair<string, int> Choices { get; set; }
	public List<string> VotedIPs { get; set; }
	public List<int?> VotedUserIDs { get; set; }
}

Here are the issues, I observe in your code

Eagle_f90

.Select(c => new

You are using anonymous type and hence you are getting the error, you need to specify the datatype as below

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select new KeyValuePair<string, int>(c.Choice, c.Votes)
						})
						.ToList();

You should make your Choices to be a list of keyvaluepair

public List<KeyValuePair<string, int>> Choices { get; set; }


Eagle_f90

model = db.yaf_Poll		
.Where(p => p.PollID == model.ID) .Select(p => new { model.Question = p.Question, model.IsMultipleChocie = p.AllowMultipleChoices, model.ExperationDate = p.Closes }) .First();

With this step you are overriding your previous step of setting Model.ID. Also you need to change the "new" to something like I mentioned above.

[RESOLVED]edit.cshtml(scaffold), validate database field to accept only 3 value

Hi!

In edit.cshtml(scaffold) I have field1(from database):

<div
class="editor-field">

            @Html.EditorFor(model => model.field1)

            @Html.ValidationMessageFor(model => model.field1)   

</div>

       

    How can I   validate field1(string type)

     to accept only 3  value  ( ex: value1, value2, value3) ?

  Thanks!

Did you meant that comma separted value in a text box?

Hi fvi,

For this requirement, you could use RegularExpressionAttribute class or custom validation.

More information, please refer to:

# RegularExpressionAttribute Class

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.110).aspx

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Best Regards

Starain Chen

[RESOLVED]how to automatically generate my sitemap.xml

Hi, i understood that the sitemap.xml is important to be on google… than i would like to know if there is an easy script in MVC to generate it aoutomatically.

I want this because my site is a little blog and i update it daily…

another thing that i need to do is the fact that my blog is done in 4 languages ENG, FRA, ITA ESP, so i would love to know ow it works for the site map to be in 4 languages and than ow to generate it..

Thanks

Hi grafic,

As far as I know, there isn’t the script to generate the SiteMap file automatically in ASP.NET MVC.

You need do it by yourself.

There are some articles that can help you:

# Generating dynamic XML Sitemaps in ASP.NET MVC

http://benfoster.io/blog/generating-dynamic-xml-sitemaps-in-aspnet-mvc

# Dynamically create google SiteMap with ASP.NET

http://blog.divergencehosting.com/2009/04/01/dynamic-create-google-sitemap-aspnet/

Best Regards

Starain Chen