【问题标题】:MVC4 Pass Model from View to ControllerMVC4 将模型从视图传递到控制器
【发布时间】:2014-07-29 02:34:31
【问题描述】:
//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>

抱歉,我对视图部分不太擅长,但我希望你能看到我在这里的目标。

另外,我正在进行需要表单 ID 的验证。我注意到使用 HTML Helper 制作表单时没有表单 ID。那会破坏我写的CSS。

任何帮助将不胜感激。

谢谢

【问题讨论】:

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


    【解决方案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 in Car Controller.

    但是正如您在问题中提到的,我们不能在 html 帮助程序中提供 id,这是错误的,例如:

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

    上面的 BeginForm() 将呈现与以下相同的 html:

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

    【讨论】:

    • 但是这个 "
      " 正确吗?这只是一个疯狂的猜测.. 我没有看到模型在哪里被传回
    • 好的,我现在只是测试一下。为 id 技巧 +1
    • 不起作用。我无法绑定到 value="@model.name"
    • 确实有效.. 我不敢相信它这么简单。它已经奏效了。您只需命名属性以匹配模型。
    • 是的...很高兴看到它对您有用...@Proximo
    猜你喜欢
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2018-01-01
    • 2013-07-08
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多