2017-09-15 56 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

相關問題