在编辑中显示值

时间:2017-06-07 08:11:41

标签: c# sql-server asp.net-mvc

我一直在尝试在editContact页面中显示我的编辑值。关于我应该如何解决这个问题,我的想法用完了。

这是我的编辑控制器

[HttpGet]
public ActionResult editContact(int? id)
{
    var databaseModel = new database();

    if (id == null)
    {
        return RedirectToAction("Index");
    }

    IEnumerable<contact> contact = databaseModel.displayContact(id);

    return View(contact);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
    try
    {
        programEntities db = new programEntities();
        var databaseModel = new database();

        if (databaseModel.editContact(editModel, id))
        {
            ViewBag.AlertMsg = "Contact edited successfully";
            return RedirectToAction("Index");
        }

        return View();
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}

在我的模型中,我有这个控制数据库操作的代码

   public List<contact> displayContact(int? Id)
   {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            List<contact> contactList = new List<contact>();

            SqlDataAdapter da = new SqlDataAdapter(comObj);
            DataTable dt = new DataTable();

            //conn.Open();
            da.Fill(dt);
            conn.Close();

            contactList = (from DataRow dr in dt.Rows
                           select new contact()
                           {
                               contactId = Convert.ToInt32(dr["contactId"]),
                               establishmentType = Convert.ToString(dr["establishmentType"]),
                               ownerName = Convert.ToString(dr["ownerName"]),
                               address = Convert.ToString(dr["address"]),
                               city = Convert.ToString(dr["city"]),
                               region = Convert.ToString(dr["region"]),
                               mobileNumber = Convert.ToString(dr["mobileNumber"]),
                               phoneNumber = Convert.ToString(dr["phoneNumber"])
                           }).ToList();

            return contactList;
        }
}

我的观点标记:

@model directory.Models.contact

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>contact</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.contactId)

    <div class="form-group">
        @Html.LabelFor(model => model.establishmentType, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.establishmentType, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ownerName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ownerName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.region, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.region, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.region, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.mobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mobileNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.phoneNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

我尝试创建一个不同的查询来显示编辑值,但异常显示我的dispayContact存储过程即使存在也不存在。除了这个之外,我的其他存储过程运行良好。

修改

所以我在SQL Server中修复了我的存储过程;它被命名为“dispayContact”。即使添加了firstOrDefault(),然后将我的视图中的声明从@model directory.Models.contact更改为@model IEnumerable<directory.Models.contact>

,编辑值仍然无法显示

2 个答案:

答案 0 :(得分:4)

我认为问题是因为您要返回一个列表

return View(contact);

其中contactIEnumerable<contact>且您的视图模型为

@model directory.Models.contact

我猜你的代码应该在返回模型后工作,而不是列表包含模型,在你的情况下返回联系人列表的FirstOrDefault()

类似这样的事情

return View(contact.FirstOrDefault());

答案 1 :(得分:1)

您的功能几乎没有问题。您可以使用比数据采用者快得多的datareader。您也不需要返回集合,只需要返回类型的对象:

获取对象的功能:

public contact displayContact(int? Id)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            using (SqlDataReader dr = comObj.ExecuteReader())
            {
                while (dr.Read())
                {
                    return new contact
                    {
                        contactId = int.Parse(dr["contactId"].ToString()),
                        establishmentType = dr["establishmentType"].ToString(),
                        ownerName = dr["ownerName"].ToString(),
                        address = dr["address"].ToString(),
                        city = dr["city"].ToString(),
                        region = dr["region"].ToString(),
                        mobileNumber = dr["mobileNumber"].ToString(),
                        phoneNumber = dr["phoneNumber"].ToString()
                    };
                }
            }
        }

        conn.Close();
    }
    return null;
}

控制器操作:

public ActionResult editContact(int? id)
    {
            var databaseModel = new database();
            if (id == null)
            {
                return RedirectToAction("Index");
           }
        var contact = databaseModel.displayContact(id);
        return View(contact);
    }