ASP.net MVC 2.0 using the same form for adding and editing

I would like to use the same view to edit a blog post and add a blog post. However, I have a problem with the ID. When adding a blog post, I don’t need to post an id value. When binding to a model binds the form values ​​to an object BlogPostin the controller, it will automatically generate an identifier in the entity of the entity frame.

When I edit a blog post, I need a hidden form field to store the identifier so that it accompanies the next form post. Here is the view I have right now.

<% using (Html.BeginForm("CommitEditBlogPost", "Admin"))
       { %>
            <% if (Model != null)
               { %>
                    <%: Html.HiddenFor(x => x.Id)%>
            <% } %>
            Title:<br />
            <%: Html.TextBoxFor(x => x.Title, new { Style = "Width: 90%;" })%>
            <br />
            <br />
            Summary:<br />
            <%: Html.TextAreaFor(x => x.Summary, new { Style = "Width: 90%; Height: 50px;" }) %>
            <br />
            <br />
            Body:<br />
            <%: Html.TextAreaFor(x => x.Body, new { Style = "Height: 250px; Width: 90%;" })%>
            <br />
            <br />
            <input type="submit" value="Submit" />
    <% } %>

, , NULL, , , , , , , , . , Model != null false, , . ID , , .

.

: OJ , -, , , - . , / , . , , , GET URL BlogProject/Admin/AddBlogPost

URL- , . POST URL- . BlogPost , EF .

URL- BlogProject/Admin/EditBlogPost/{Id} URL- , URL-, POST , .

, , , .

[HttpGet]
public ViewResult EditBlogPost(int Id)
{

}

[HttpPost]
public ViewResult EditBlogPost(int Id)
{

}

, . , Id Html.BeginForm() . POST , FormCollection. :

[HttpPost]
public ViewResult EditBlogPost(int Id, FormCollection formCollection)
{
     // You can then use formCollection as the IValueProvider for UpdateModel()
     // and TryUpdateModel() if you wish. I mean, you might as well use the
     // argument since you're taking it.
}

formCollection , Request.Form. UpdateModel() TryUpdateModel(), , , , , GET.

, ! , . , , - , .

+3
2

:

  • Id Nullable HasValue.
  • ViewData mode .
  • : .
+2

:

  • URL- ,
  • ,

, .

+2

Source: https://habr.com/ru/post/1792673/


All Articles