从视图到控制器的MVC4传递模型

时间:2014-07-29 02:34:31

标签: forms asp.net-mvc-4 post view model

//Model
public class Car
{
   string name{get;set;}
   double speed {get;set;}
   //etc.
}

基本型号

//Controller
public ActionResult ModifyCar(Car c)
{
    c = GetAdditionalData(c.name, c.speed);
    return View(c);
}

因此,我打电话给外部服务以获取汽车的其他数据。

以下是我真正感到困惑的表格。我只想用HTML写这个。

但是从这里开始我想采用一个基本的空模型..填充它然后发送给控制器以获取更多数据。

//View
@model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
    <input id="carName"  /> //Somehow bind with @model.name
    <input id="carSpeed" /> //Somehow bind with @model.speed
    <input type="submit" /> //Somehow send the model to the controller
</form>

对不起,我根本不擅长View部分,但我希望你能看到我要去的地方。

另外,我正在进行需要表单ID的验证。我注意到使用HTML Helper制作表单时没有表单ID。多数民众赞成打破了我写的CSS。

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

@model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" name="carName" value=@Model.name  /> //Somehow bind with @model.name
<input id="carSpeed" name="carSpeed" value=@Model.speed /> //Somehow bind with @model.speed
<input type="submit" value="Submit" /> //Somehow send the model to the controller
</form>

当您的表单提交时,将转到ModifyCar中的action Car Controller

但正如你在问题中提到的那样我们不能在html助手中给出id,我们可以为ex做错:

@using(Html.BeginForm("ModifyCar","Car",FormMethod.Post,new{ id="carform" }))

上面的BeginForm()会渲染相同的html:

<form id="carform" method="post" action="/Car/ModifyCar">