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

2019-10-19 12:32发布

This question already has an answer here:

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

2条回答
老娘就宠你
2楼-- · 2019-10-19 12:44

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.

查看更多
走好不送
3楼-- · 2019-10-19 13:03

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
     }
}
查看更多
登录 后发表回答