将Razor变量分配给Javascript变量时出现Javascript语法错误

时间:2016-08-11 21:08:58

标签: javascript asp.net-mvc razor

非常奇怪的行为,我无法理解剃刀变量完全消失的位置,如截图所示(@SomeID消失)。我的目标是从服务器获取id,然后将其分配给javascript变量。当razor变量为null时,无论我在哪里分配此变量,即使文档就绪,也会出现问题。

观点:

import SafariServices

let kSafariViewControllerCloseNotification = "kSafariViewControllerCloseNotification"

// facebook OAuth URL
let authURL = NSURL(string: "https://www.facebook.com/dialog/oauth?client_id=3627644767&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=basic_info,email,public_profile,user_about_me,user_activities,user_birthday,user_education_history,user_friends,user_interests,user_likes,user_location,user_photos,user_relationship_details&response_type=token")

class ViewController: UIViewController, SFSafariViewControllerDelegate {

    var safariVC: SFSafariViewController?
    @IBOutlet weak var loginButton: UIButton!

    @IBAction func loginButtonTapped(sender: AnyObject) {
        safariVC = SFSafariViewController(URL: authURL!)
        safariVC!.delegate = self
        self.presentViewController(safariVC!, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.safariLogin(_:)), name: kSafariViewControllerCloseNotification, object: nil)
    }

    func safariLogin(notification: NSNotification) {
        // get the url from the auth callback
        let url = notification.object as! NSURL
        // Finally dismiss the Safari View Controller with:
        self.safariVC!.dismissViewControllerAnimated(true, completion: nil)
    } 

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func safariViewControllerDidFinish(controller: SFSafariViewController) {
        controller.dismissViewControllerAnimated(true) { () -> Void in
            print("You just dismissed the login view.")
        }
    }

    func safariViewController(controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print("didLoadSuccessfully: \(didLoadSuccessfully)")

    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

假设SomeID变量有一些像2545这样的值。 Razor会像下面一样呈现你的代码。

testVariable = 2545; 

但是你的变量是可空的类型。这意味着它可能具有null值。我相信您的ViewBag.BoxID值为null,因此您的变量变为null并且生成的HTML变为

function OnElementLoaded() {
    testVariable = ;
}

您可以做的一件事是将值包装在引号中。但这最适合非数值(字符串)。

function OnElementLoaded() {
    testVariable = `@SomeID`; 
} 

对于数值,最好进行空检查并赋值。如果c#表达式的值为null,则设置为0(或任何您想要的默认值);

例如,如果ViewBag.BoxID表达式返回null,则下面的代码将设置为0.

@{
    long? SomeID = ViewBag.BoxID!=null ? (long?)ViewBag.BoxID:0;
}

<script type="text/javascript">
    var testVariable;

    function OnElementLoaded() {
        testVariable = @SomeID;

    }
</script>