Question

I am trying to pass Strongly Typed ViewBag from Controller to View, then from View call a static method on jquery link click which uses the View bag property as paramater.

In Controller, I have

public ActionResult LoginUser(string userName, string password)
{
    MyMembershipUser myUser = runtime.MyMembership.GetUser(userName);
    **ViewBag.MyUser = myUser;** //Here I assign user to ViewBag so I can pass it to                            
    return View("Login");        // View and from there as paramater to static method.

}

Below in my "Login" View I have code for calling my SendEmail static method inside script.

     <div id="login">
            <p>    
          <span class="link" id="link">Generate Email.</span><br />
            </p>
        </div>  

<script type="text/javascript">
    $('#link').click(function () {           
        @SendEmailClass.SendEmail(ViewBag.MyUser);// Here I pass User from ViewBag to       
                                                  // static Method
    });
</script>

Below is my Static Class with Static method.

public static class SendEmailClass
 {
      public static void SendEmail(MyMembershipUser myUser)
      {
        SendEmail(myUser, string.Empty, string.Empty, string.Empty, string.Empty);
      }
}

As control tries to call static method from View.it fails with Exception as "Cannot Implicitly convert type 'void' to 'Object'".

Even if i try to cast it at method call ,something like this @SendEmailClass.SendEmail((MyMembershipUser)ViewBag.MyUser) it gives same error.

Is it some problem with my action method return type ? I don't want to return anything here. I just want to send email.

Était-ce utile?

La solution

You can't call a static method written in C# directly from javascript.

It is throwing the Exception "Cannot Implicitly convert type 'void' to 'Object'" because the method SendEmail returns "void", and when you use a @ followed by a method, razor is expecting an Object to print.

You could make another Action in your Controller where you call the SendMail method, in your link you could use ajax to call this Action and pass the parameters that you are needing from the MyMembershipUser object.

To use ajax with Jquery you could start reading this: http://api.jquery.com/jQuery.get/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top