ASP.NET MVC 3 Model-binding and form fields

后端 未结 3 348
醉酒成梦
醉酒成梦 2020-12-31 18:05

I have an entity called Domain.Models.BlogPost which contains the following properties:

  • PostID
  • Title
  • Author
  • PostedDate<
相关标签:
3条回答
  • 2020-12-31 18:48

    You could either rename the fields in the AddComment section to something that does not collide with the properties named in the Model, or you could override the value in the view using a different overload of Html.TextBox This overload of TextBox takes a value:

    value (Type: System.Object)
    The value of the text input element. If this value is null, the value of the element is retrieved from the ViewDataDictionary object. If no value exists there, the value is retrieved from the ModelStateDictionary object.


    UPDATE: Since you added "NewComment" as a property and resolved the property naming collision that way, all that you need to do to bind a PostComment rather than the whole view model on POST to the action, is to instruct the model binder that a prefix will be used. This is done using the BindAttribute.

    public ActionResult AddComment([Bind(Prefix = "NewComment")] PostComment postComment)
    
    0 讨论(0)
  • 2020-12-31 18:53

    Use ASP NET MVC templates so you have full control over what gets populated and it is type-safe.

    So you would create an .ascx template which takes a strongly typed Comment. In your model, you leave an empty one in there.

    0 讨论(0)
  • 2020-12-31 19:00

    Isn't there an overload on TextBox that takes a value? You could just pass string.Empty...

    0 讨论(0)
提交回复
热议问题