C#MVC将字符串中的变量绑定到模型
在C#MVC将字符串中的变量绑定到模型,c#,asp.net-mvc,properties,C#,Asp.net Mvc,Properties,在C#MVC中,可以使用模型绑定自动将变量解析到模型中 public class RegistrationForm { string Name {get;set;} string Address {get;set;} } public ActionResult Register(RegistrationForm register) { ... } 如果我传递名称和地址变量,它们将直接在寄存器对象中可用 如果字符串中有变量,是否可以手动调用此绑定? 例如: 我知道我可以使用HttpUti
C#MVC
中,可以使用模型绑定自动将变量解析到模型中
public class RegistrationForm {
string Name {get;set;}
string Address {get;set;}
}
public ActionResult Register(RegistrationForm register) {
...
}
如果我传递名称
和地址
变量,它们将直接在寄存器
对象中可用
如果字符串中有变量,是否可以手动调用此绑定?
例如:
我知道我可以使用
HttpUtility.ParseQueryString获得NameValueCollection
然后使用反射来获取注册表单的属性,并检查这些值是否存在,但我希望我可以使用MVC使用的实际绑定方法。MVC绑定基于视图模型的属性名称(注册表单
类)
所以您完全正确,如果您使用GETHTTP方法从字符串绑定属性,您可以直接编写:
这是区分大小写的,小心点
或者,如果您使用Razor生成链接,您可以将其写得更清楚:
@Url.Action("Register", new { Name = "hugo", Address = "test"})
您可以模拟传递到Modelbinding中的HttpContext,如下所示
您可以将字符串转换为JSON对象,然后使用序列化程序将JSON对象解析为您的模型。@Malcolm的anwser是我请求的,因此他获得了积分。但我最终还是用反思来做,因为在我看来,它看起来更干净,更容易理解正在发生的事情
var result = HttpUtility.ParseQueryString(strResponse);
Type myType = GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
prop.SetValue(this,
Convert.ChangeType(result[prop.Name], prop.PropertyType, CultureInfo.InvariantCulture),
null);
}
catch (InvalidCastException)
{
//skip missing values
}
catch (Exception ex)
{
//something went wrong with parsing the result
new Database().Base.AddErrorLog(ex);
}
}
var result=HttpUtility.ParseQueryString(strResponse);
类型myType=GetType();
IList props=新列表(myType.GetProperties());
foreach(PropertyInfo props in props)
{
尝试
{
prop.SetValue(此,
Convert.ChangeType(结果[prop.Name]、prop.PropertyType、CultureInfo.InvariantCulture),
无效);
}
捕获(无效卡斯特例外)
{
//跳过缺少的值
}
捕获(例外情况除外)
{
//解析结果时出错
新建数据库().Base.AddErrorLog(ex);
}
}
免责声明
这对我很有用,因为我只得到字符串和小数,不需要任何东西。这与MVC模型活页夹完全不同。是的,我知道我是对的:),但我没有从查询字符串或POST中获取值,而是将它们保存在字符串变量中。他们错误地编辑了我的问题。好吧,你是说在js
变量中?您也可以使用js
来执行此操作<代码>window.location.href=http://yourSite.com/YourController/Register?“+s代码>但别忘了大小写。@teovankot:不,是一个C#字符串。不,我的意思是一个字符串myvariables=“name=hugo&address=test”
我已经在一个控制器/动作中,我有一个变量,我想解析成一个模型。我不同意“区分大小写”的说法。如果你编辑我的问题,请不要改变它的意思。谢谢,这就是我需要的。不幸的是,这比使用反射还要多(实际上要多得多)。我基本上是从头开始构建一个全新的页面请求来绑定这些值。
var controllerContext = new ControllerContext();
//set values in controllerContext here
var bindingContext = new ModelBindingContext();
var modelBinder = ModelBinders.Binders.DefaultBinder;
var result = modelBinder.BindModel(controllerContext, bindingContext)
var result = HttpUtility.ParseQueryString(strResponse);
Type myType = GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
prop.SetValue(this,
Convert.ChangeType(result[prop.Name], prop.PropertyType, CultureInfo.InvariantCulture),
null);
}
catch (InvalidCastException)
{
//skip missing values
}
catch (Exception ex)
{
//something went wrong with parsing the result
new Database().Base.AddErrorLog(ex);
}
}