当我回发观点时,如何判断发生了什么?

时间:2013-12-17 05:50:56

标签: asp.net-mvc-4

我正在使用MVC 4 EF Code First,我有一个带有编辑视图的对象,它可以正常工作。然后我创建了一个非常相似的创建视图,只有当我点击提交按钮时,我才在控制器中点击任何断点。我怎么知道这里有什么问题?有没有我可以在JavaScript或代码隐藏中设置断点的地方?

模型

public class ThirdParty : BaseModel
{
    public Int32 Id { get; set; }

    [MaxLength(2)]
    private String CountryCode { get; set; }

    [MaxLength(6)]
    private Int32 SequenceNumber { get; set; }

    public String UIN 
    { 
        get 
        {
            if (CountryCode != null && SequenceNumber > 0)
                return CountryCode.ToString() + "-" + SequenceNumber.ToString();
            else
                return null;
        }
        set
        {
            CountryCode = value.ToString().Substring(0, 2);
            SequenceNumber = Int32.Parse(value.ToString().Substring(3, value.Length-3));
        }

    }

    [MaxLength(250)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "{0} is required.")]
    public String Name { get; set; }

    public virtual ICollection<RelationshipType> RelationshipTypes { get; set; }

    // Address
    public Int32 AddressId { get; set; }
    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

    public bool IsImported { get; set; }

    public bool IsActive { get; set; }

    public virtual ICollection<Attachment> Attachments { get; set; }

    // constructor
    public ThirdParty()
    {
        RelationshipTypes = new HashSet<RelationshipType>();
        Attachments = new HashSet<Attachment>();
    }
}

控制器方法

public ActionResult Edit(int id)
    {
        ThirdPartyContext context = new ThirdPartyContext();
        ThirdParty model = context.ThirdParties.Find(id);
        ViewBag.Countries = context.Countries.ToList<Country>();
        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(string button, ThirdParty model, int id)
    {
        if (button == "cancel")
            return RedirectToAction("Index");

        if (ModelState.IsValid)
        {
            ThirdPartyContext context = new ThirdPartyContext();


            model.Address.Country = context.Countries.Find(model.Address.CountryId);
            context.Entry(model.Address.Country).State = EntityState.Modified;
            context.Entry(model.Address).State = EntityState.Modified;
            context.Entry(model).State = EntityState.Modified;
            context.SaveChanges();

            Success("Third Party record updated!");
            return RedirectToAction("Index");
        }
        else
        {
            ThirdPartyContext context = new ThirdPartyContext();
            model.Address = context.Addresses.Find(model.AddressId);
            return View("Edit", model);
        }
    }

    public ActionResult Create()
    {
        ThirdPartyContext context = new ThirdPartyContext();
        ViewBag.Countries = context.Countries.ToList<Country>();
        return View();
    }

    [HttpPost]
    public ActionResult Create(ThirdParty model)
    {
        if (ModelState.IsValid)
        {
            ThirdPartyContext context = new ThirdPartyContext();
            List<ThirdParty> models = context.ThirdParties.ToList<ThirdParty>();
            model.Id = models.Count() == 0 ? 1 : models.Select(x => x.Id).Max() + 1;
            context.ThirdParties.Add(model);
            context.SaveChanges();

            Success("Your information was saved!");
            return RedirectToAction("Index");
        }
        Error("There were some errors in your form.");
        return View(model);
    }

    [HttpPost]
    public ActionResult Create(string button, ThirdParty model)
    {
        if (button == "cancel")
            return RedirectToAction("Index");

        if (ModelState.IsValid)
        {
            ThirdPartyContext context = new ThirdPartyContext();
            List<ThirdParty> models = context.ThirdParties.ToList<ThirdParty>();
            model.Id = models.Count() == 0 ? 1 : models.Select(x => x.Id).Max() + 1;
            context.ThirdParties.Add(model);
            context.SaveChanges();

            Success("Your information was saved!");
            return RedirectToAction("Index");
        }
        Error("There were some errors in your form.");
        return View(model);
    }

修改视图

@model Models.ThirdParty

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/shared/ContentLayout.cshtml";
}


<div class="row">
    <div class="col-lg-12">
        <div class="page-header">
            <h2>Third Party</h2>
        </div>
    </div>
</div>

<div class="row">
     <div class="col-lg-8">
@using (Html.BeginForm("Edit", "ThirdParty", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.HiddenFor(model => model.Id)
        <div class="clearfix visible-xs"></div>
        @Html.HiddenFor(model => model.Address.Id)
    </div>
    <div class="form-group">
        @Html.EditorFor(model => model.UIN)
        <div class="clearfix visible-xs"></div>
        @Html.EditorFor(model => model.Name)
    </div>

    @Html.HiddenFor(model => model.AddressId)
    @Html.Partial("_EditAddress", Model)

    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.CreatedOn)
    @Html.HiddenFor(model => model.ModifiedBy)
    @Html.HiddenFor(model => model.ModifiedOn)

    <p>
        <button name="button" type="submit" class="btn btn-default" value="cancel">Cancel</button>
        <button name="button" type="submit" class="btn btn-primary" value="submit">Submit</button>
    </p>
}

    </div>
</div>

**创建视图**

@model Models.ThirdParty

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/shared/ContentLayout.cshtml";
}

<div class="row">
    <div class="col-lg-12">
        <ul class="breadcrumb" style="margin-bottom: 5px;">
            <li><a href="#">Third Parties</a></li>
            <li class="active">Create New Third Party</li>
        </ul>
    </div>
</div>

<div class="row">
    <div class="col-lg-12">
        <div class="page-header">
            <h2>Create Third Party</h2>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-2">&nbsp;</div>
    <div class="col-lg-8">
        @using (Html.BeginForm("Create", "ThirdParty", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal" }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            @Html.EditorFor(model => model.UIN)

            @Html.EditorFor(model => model.Name)

            @Html.HiddenFor(model => model.AddressId)
            @Html.Partial("_EditAddress", Model)

            @Html.HiddenFor(model => model.CreatedBy)
            @Html.HiddenFor(model => model.CreatedOn)
            @Html.HiddenFor(model => model.ModifiedBy)
            @Html.HiddenFor(model => model.ModifiedOn)

            <p>
                <button name="button" type="submit" class="btn btn-default" value="cancel">Cancel</button>
                <input name="button" type="submit" class="btn btn-primary" value="submit" title="Submit" />
                <input type="submit" value="Create" />
            </p>
        }
    </div>
    <div class="col-lg-2">&nbsp;</div>
</div>

修改

我可能遗漏了一个关键部分。我在ThirdParty和Address模型上有这四个隐藏字段,我计划在控制器Create方法中设置(如果我可以进入那里)。这是模型:

public class BaseModel
{
    [HiddenInput(DisplayValue = false)]
    public Int32 CreatedBy { get; set; }

    [HiddenInput(DisplayValue = false)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime CreatedOn { get; set; }

    [HiddenInput(DisplayValue = false)]
    public Int32 ModifiedBy { get; set; }

    [HiddenInput(DisplayValue = false)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime ModifiedOn { get; set; }
}

我在想,也许我的观点无效,这也就是为什么它不会将它发送给控制器。以下是页面标记中的内容:

    <input data-val="true" data-val-number="The field CreatedBy must be a number." data-val-required="The CreatedBy field is required." id="Address_CreatedBy" name="Address.CreatedBy" type="hidden" value="" />
    <input data-val="true" data-val-date="The field CreatedOn must be a date." data-val-required="The CreatedOn field is required." id="Address_CreatedOn" name="Address.CreatedOn" type="hidden" value="" />
    <input data-val="true" data-val-number="The field ModifiedBy must be a number." data-val-required="The ModifiedBy field is required." id="Address_ModifiedBy" name="Address.ModifiedBy" type="hidden" value="" />
    <input data-val="true" data-val-date="The field ModifiedOn must be a date." data-val-required="The ModifiedOn field is required." id="Address_ModifiedOn" name="Address.ModifiedOn" type="hidden" value="" />



        <div class="form-group">
            <input data-val="true" data-val-number="The field CreatedBy must be a number." data-val-required="The CreatedBy field is required." id="CreatedBy" name="CreatedBy" type="hidden" value="" />
            <input data-val="true" data-val-date="The field CreatedOn must be a date." data-val-required="The CreatedOn field is required." id="CreatedOn" name="CreatedOn" type="hidden" value="" />
            <input data-val="true" data-val-number="The field ModifiedBy must be a number." data-val-required="The ModifiedBy field is required." id="ModifiedBy" name="ModifiedBy" type="hidden" value="" />
            <input data-val="true" data-val-date="The field ModifiedOn must be a date." data-val-required="The ModifiedOn field is required." id="ModifiedOn" name="ModifiedOn" type="hidden" value="" />
        </div>

1 个答案:

答案 0 :(得分:1)

如果您的操作被调用,则在操作开始时设置断点并附加到该过程应该可以解决问题。 当您在“创建”页面上单击“提交”时,是否确保从浏览器发送了POST请求?

我没有尝试运行您的代码,但请注意您已经定义了两个具有相同名称的Create操作来处理POST动词。

对于ASP.NET MVC来说,这可能是模棱两可的,因为它无法确定要调用的操作。

此外,您在以下行中定义了ReturnUrl路由值:

@using (Html.BeginForm("Create", "ThirdParty", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal" }))

在您处理POST的操作中似乎没有使用此功能。

为什么你有2个提交按钮,其值为“submit”和“create”?

您可以删除采用额外按钮参数的Create操作并替换标记:

<button name="button" type="submit" class="btn btn-default" value="cancel">Cancel</button>
                <input name="button" type="submit" class="btn btn-primary" value="submit" title="Submit" />
                <input type="submit" value="Create" />

有类似的东西:

<a class="btn btn-default" href="@Url.Action("Index", "ThirdParty")">Cancel</a>
<input name="button" type="submit" class="btn btn-primary" value="Create" title="Create" />

我邀请您阅读有关ASP.NET MVC路由如何工作的更多documentation