将对象从视图传递到控制器 MVC 5

Pass object from view to controller MVC 5

我需要将此对象从视图传递到控制器:

public class QuoteVehicle
    {
        [DisplayName("Quote Vehicle ID")]
        public int QuoteVehicleID { get; set; }
        [DisplayName("Quote ID")]
        public int QuoteID { get; set; }
        [DisplayName("Model Year")]
        public string ModelYear { get; set; }            
        //etc...
    }

如果我在控制器中设置值,它们将传递给视图;但是如果我在视图中设置或更改值并将其传回......它到达那里,但值为空。

我正在使用这个 Ajax.BeginForm:

 @Using (Ajax.BeginForm("GetQuote", "Quote", 
         New With {.QuoteVehicle = JsonConvert.SerializeObject(Model.QuoteVehicle)},
         New AjaxOptions() With {
                                 .UpdateTargetId = "PriceOptionsPanel",
                                 .HttpMethod = "GET",
                                 .OnComplete = "SetDatePickers",
                                 .InsertionMode = InsertionMode.Replace,
                                 .LoadingElementId = "loader"
                                 }
))

我的属性在表单内如此绑定:

 @Html.TextBoxFor(Function(model) model.QuoteVehicle.Make, New With {.class = "form-control", .readonly = "readonly"})

在我的控制器中:

 Function GetQuote(QuoteVehicle As String) As ActionResult
    Dim _quoteVehicle = JsonConvert.DeserializeObject(Of QuoteVehicle)(QuoteVehicle)
    Return View(etc.)
 End Function

我也试过 <HttpPost>.HttpMenthod = "POST",但也没用。

很想知道为什么他们没有被设置...

模型看起来像这样:

Public Class MenuOptionsModel       
        Public Property VIN() As String
        Public Property QuoteVehicle() As QuoteVehicle
        Public Property IsDecoded As Boolean       
        Public Property IsNew As Boolean = False
        Public Property Is30Day As Boolean?
        Public Property IsUnderWarranty As Boolean?
    etc...
End Class

不在对象中而只是类型(即布尔值?字符串)的属性可以很好地绑定,但对象中的属性则不能。

将您的操作参数类型更改为 QuoteVehicle 并使用 HttpPost 和 .HttpMenthod = "POST"

 Function GetQuote(model As QuoteVehicle ) As ActionResult
  //now you can access to your model here
    Return View(etc.)
 End Function

所以,事实证明你不能根据你的对象来命名你的对象,比如:

Public QuoteVehicle As QuoteVehicle

然后像这样使用它:

Ajax.BeginForm("Action", "Controller", New With { .QuoteVehicle = Model.QuoteVehicle...

Function GetQuote(QuoteVehicle As QuoteVehicle) As ActionResult
   //access properties
End Function

我所要做的就是将 属性 重命名为与对象的 type/name 不完全相同的名称...例如:

Public _quoteVehicle As QuoteVehicle    
Public NotNamedQuoteVehicle As QuoteVehicle
etc...

我用了Public CurrentQuoteVehicle As QuoteVehicle

现在可以了:

Ajax.BeginForm("Action", "Controller", New With { .CurrentQuoteVehicle = Model.QuoteVehicle...

Function GetQuote(CurrentQuoteVehicle As QuoteVehicle) As ActionResult
   //access properties
End Function