2017-09-15 36 views
-1

这不是重复的线程。 我的情况是发送没有模型的数组参数。但其他线程是发送int,字符串参数个体。是否有没有模型的数组后表单的方法?

我知道如何发布与模型对象控制器。
但有时我想模型db和岗位格式对象或数组 之外发布的数据我怎么能这样做?

查看

<form action="/home/showdata" method="post"> 
    <input type="text" name="arr.username" /> 
    <input type="text" name="arr.password" /> 
    <input type="text" name="arr.email" /> 
</form> 

控制器

public class HomeController : Controller 
{ 
    [HttpPost] 
    public ActionResult ShowData(Array data) 
    { 
     return Content(data.username + data.password + data.email); 
    } 
} 
+2

为什么你要做到这一点没有一个模式? – DavidG

+0

,因为有些字段不在数据库表中。 –

+2

数据库与这里发布的模型有什么关系? – DavidG

回答

2

有许多不同种类的Models。例如。 Database ModelsView ModelsDTOs等,所以,你的情况,你从客户端接收数据从数据库模型(其中,顺便说一句,通常是这种情况)显著不同。这意味着你应该创建特定的视图模型,View Model,然后验证数据后,该传输数据到数据库模型。例如:

public class SampleViewModel { 
    public int Id { get; set;} 
    public string Name { get; set; } 
} 

然后在你的控制器:

public IHttpActionResult SampleActionMethod(SampleViewModel model) { 
    if (!ModelState.IsValid) { 
      return BadRequest(); 
    } 
    var sampleDbModel = new SampleDatabaseModel() { 
      FullName = model.Name, 
      ProductId = model.Id, 
      // ... some other properties ... 
    }; 
    // ... Save the sampleDbModel ... 
    return Ok(); // .. or Created ... 
} 

这回答只是表明你如何做你正在尝试做的。但理想情况下,无论如何,您都不应将数据库模型用作操作方法的参数。还有很多其他的事情,为此,我建议你看看Repository Pattern,Unit Of Work(用于管理数据库任务)和Automapper(用于映射的东西,如果你想要的,例如查看模型到模型)等 希望这可以帮助。

+1

哦,我误解了模型永远是数据库模型。感谢 –

0

这里最好的解决方法是使用一个模型。模型不一定与数据库表相关。

public ActionResult ShowData(Array data) 

可能是:

public ActionResult ShowData(YourModelNameHere data) 

而且你可以定义为YourModelNameHere类似:

public class YourModelNameHere 
{ 
    public string username {get; set;} 
    public string password {get; set;} 
    public string email {get; set;} 
} 
+1

我误以为模型始终是数据库模型。非常感谢。 –

1

你好,我会recomended你在控制器的FormCollection

<form action="/home/showdata" method="post"> 
    <input type="text" name="username" /> 
    <input type="text" name="password" /> 
    <input type="text" name="email" /> 
</form> 

可以使用的FormCollection

public class HomeController : Controller 
{ 

    [HttpPost] 
    public ActionResult ShowData(FormCollection data) 
    { 
     string username=data.GetValues("username")[0]; 
     string password=data.GetValues("password")[0];  
      string email=data.GetValues("email")[0]; 

     return Content(username + password + email); 
    } 
} 

此外,如果一些HTML输入具有相同的名称,那么你会得到他们的价值的字符串数组。

+0

如果你真的不想使用模型,你可以使用的FormCollection –

+0

嗨传递数据!太酷了。 –

-4

首先,你需要序列化的表格数据,并保持数据串行隐申请和后期使用后键和反序列 它得到的FormCollection这个数据。

+0

这个答案与被问到的问题没有任何关系。还将数据序列化到隐藏字段中是完全不必要的。 – DavidG

相关问题