开发者

Problem with Primary Key in a Partial View shared by Create and Edit views

开发者 https://www.devze.com 2023-01-07 14:20 出处:网络
I have a partial view (user control) that is shared by my Create and Edit views.When I use it in the Edit view, I have to to include an hidden field (Html.HiddenFor) to prevent a \'Row changed or not

I have a partial view (user control) that is shared by my Create and Edit views. When I use it in the Edit view, I have to to include an hidden field (Html.HiddenFor) to prevent a 'Row changed or not found' error in my data service, but when I use it in the Create view, I have to remove the PK hidden field, to prevent an error over trying to insert into an identity column.

It is not feasible to not use identity columns in this application, so how can I 'switch' that PK hidden field on or off depending on which action has been invoked?

Post Action Code:

    [HttpPost]
    public ActionResult Edit(JobCardViewData viewData)
    {
        try
        {
            jobCardService.Update(viewData.JobCard);

Edit View Excerpt:

<% Html.RenderPartial("JobCardInpu开发者_StackOverflow社区t", Model); %>

Partial Excerpt:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Poynting.Installation.Web.ViewData.JobCardViewData>" %>
<% using (Html.BeginForm())


when I use it in the Create view, I have to remove the PK hidden field, to prevent an error over trying to insert into an identity column.into an identity column.

Leave the hidden field and update the Create action to check if the value is 0 or null (I assume that JobCard is an argument type of the Create action). Another thought would be to re-create a new JobCard object, which excludes setting the id value, and send the new object to the jobCardService create method.

so how can I 'switch' that PK hidden field on or off depending on which action has been invoked?

You could possibly create a HtmlHelper to render the hidden field for you. Check the ViewContext RouteData collection for the the action name output the hidden field accordingly if required. (Pseudo-code..)

public static MvcHtmlString HiddenTest(this HtmlHelper htmlHelper, string name)
{
    string currentAction = htmlHelper.ViewContext.RouteData.Values["action"].ToString();
    if (currentAction = "Edit"){
     return htmlHelper.Hidden(htmlHelper, name);
    }
   return null;
}


can you have your PK in the url?

ThingController/Create

ThingController/Edit/1234

0

精彩评论

暂无评论...
验证码 换一张
取 消