-1

I am trying to pass the whole Model object with one other parameter to js function launchMyActivity(). but the function is not getting it. When I did the aler(passedObject.length) it is giving unidentified.

I have tried other things but nothing worked.Referred this but didnt worked

I am not sure what is wrong with my implementation.

Model :

public class RequestDTO
{
    public HttpRequestBase RequestDto { get; set; }
    public List<User> Users { get; set; }
    public string ActionId { get; set; }
    public string UserSampleID { get; set; }
}

View :

@model RequestDTO
<body>
        @Scripts.Render("~/bundle/js/Area/SelectedStudentActivity")
        <div class='popOver' style="z-index: 1012;">
            <div id='popOverMsg'>Select the student you want to Launch this Activity for:..</div><br /><br />
            @foreach(var user in Model.Users)
            {                
                <a id="selectedAnchor" data-id="@user.id" style="cursor:pointer" onclick="launchMyActivity(@user.UserID,@Model)">@user.name</a><br />
            }
        </div>
</body>

JS :

function launchMyActivity(studentSISId, requestDTO)
{
    alert("Lenght : " + requestDTO.length); //I get undefined here

    //Below this I need to make AJAX call and pass this requestDTO object.
}
Community
  • 1
  • 1
TolerantCoder
  • 53
  • 1
  • 5
  • Model is a C# object but you are trying to pass it into javascript. You will need to jsonify it so javascript understands it. – nurdyguy Apr 25 '16 at 20:02
  • Try this: http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4 – nurdyguy Apr 25 '16 at 20:07
  • Are you using CSHTML?? Try this function launchMyActivity(studentSISId) { alert("Lenght : " + @Model.length); } – Shan Mar 23 '17 at 16:51

1 Answers1

0

You should not be passing HttpRequestBase to javascript. First of all, as you discovered this won't work. Your C# code is executed by .Net runtime on your web server. Javascript is executed by web browser on the client machine. These two are completely different execution systems and you cannot really pass semantic between the two.

HttpRequesBase, citing MSDN, "Serves as the base class for classes that enable ASP.NET to read the HTTP values sent by a client during a Web request". You do not have asp.net on your browser and this class along with it's methods does not make sense on the client.

What you need to do instead is define your model. It is your model, that you want to pass between server and client. Extract whatever information that is meaningful for the client from HttpRequesBase, and put it to the model. A model is usually a simple class without any behaviour (methods) and just has a number of properties that are trivially serialized to json. There is quite a lot of easy to find information how to this bit for models like that.

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158