2

我使用 MVC 3,我有一个控制器,代码如下?

// GET: /ManageAdvSlots/Delete/5

    public ActionResult Delete(int id)
    {
        AdvSlot advSlot = advSlotRepository.FindById(id);
        AdvSlotDeleteViewModel deleteViewModel = Mapper.Map<AdvSlot, AdvSlotDeleteViewModel>(advSlot);
        return View(deleteViewModel);
    }

    //
    // POST: /ManageAdvSlots/Delete/5

    [HttpPost]
    public ActionResult Delete(AdvSlotDeleteViewModel deleteViewModel)
    {
        if (ModelState.IsValid)
        {
            AdvSlot advSlot = Mapper.Map<AdvSlotDeleteViewModel, AdvSlot>(deleteViewModel);
            advSlotRepository.Delete(advSlot.AdvSlotId);
            advSlotRepository.Save();
        }
        return RedirectToAction("Index");
    }
}

看法

@model MyProject.ViewModels.AdvSlotDeleteViewModel

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>AdvSlotDeleteViewModel</legend>

    <div class="display-label">AdvSlotId</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.AdvSlotId)
    </div>

    <div class="display-label">Name</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>

    <div class="display-label">Description</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Description)
    </div>

    <div class="display-label">IsPublished</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.IsPublished)
    </div>

    <div class="display-label">Code</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Code)
    </div>

    <div class="display-label">Note</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Note)
    </div>
</fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}

查看模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyProject.ViewModels
{
    public class AdvSlotDeleteViewModel
    {
        public int AdvSlotId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsPublished { get; set; }
        public string Code { get; set; }
        public string Note { get; set; }
    }
}
4

2 回答 2

5

您需要将所有表单字段放在表单块中。否则它们将不会被发布到服务器。

移动你的<fieldset>内心@using (Html.BeginForm()) { ->> HERE <<- }

PS。对于删除,您可能只想发布id,而不是整个视图模型。

于 2012-07-04T11:43:14.097 回答
1

人们建议在隐藏的表单字段中仅包含 id 就足够了:

@using (Html.BeginForm()) {
@Html.HiddenFor(x => x.AdvSlotId)
<p>
    <input type="submit" value="Delete" /> |
    @Html.ActionLink("Back to List", "Index")
</p>
}

您可能会发现您不想再检查模型是否有效。如果您对某些字段进行了高级验证,如果它们不在表单内,它们将不会被发回。例如,如果需要“名称”,则上述代码的验证将失败,因为只有表单内的字段会回传到服务器。

于 2012-07-04T11:52:16.583 回答