How to cast variable from string to int in MVC .AS

2019-10-19 12:18发布

问题:

This question already has an answer here:

  • How can I convert String to Int? 27 answers

I have this variable in MVC .ASP NET Razor Synthax:

    var data = System.Web.HttpContext.Current.Request.Form["data"];

var data is a string. Is there any way i can type cast it into int?

thanks

回答1:

You're looking for:

var intData = Convert.ToInt32(System.Web.HttpContext.Current.Request.Form["data"]);

But you definatly should read about MVC model binding. And name conversations and ViewModels and Strongly Typed Views.

When you understand how it work you won't need this convertions anymore.



回答2:

In razor, you can use @{ //c# code } syntax.. Try this;

@{

int value; 
if (int.TryParse(Request.Form["data"], out value)) 
    { 
    // it's a number use the variable 'value' 
    } else { 
    // not a number
     }
}