0

I just want to edit my old data using mvc4. For eg, the city name needs to be changed from chennai (dropdownlist which is populated from model) to pune. Can anyone guide me pls?

Below is my code:

Controller:

[HttpGet]
    public ActionResult display(Create model)
    {

        List<Create> city = new List<Create>();
        using (connectionstring pcs = new connectionstring())
        {
            city = pcs.grp.OrderBy(a => a.cityname).ToList();

        }
        ViewBag.cityname = new SelectList(city, "cityname", "cityname");
        return View(model);

    }

    [HttpPost, ActionName("display")]
    [ValidateAntiForgeryToken]
    public ActionResult display1( Create cg)
    {

        List<Create> city = new List<Create>();
        using (connectionstring pcs = new connectionstring())
        {
            city = pcs.grp.OrderBy(a => a.cityname).ToList();

        }
    ViewBag.cityname = new SelectList(city, "cityname", "cityname");

        if (ModelState.IsValid) 
        {


            string oldgcityname = cg.cityname.ToString().Trim();
    using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["portalconnectionstring"].ConnectionString))
            {

                       using( NpgsqlCommand cmd=new NpgsqlCommand("update tblcity set cityname='$1' where cityname='"+oldcityname+"'",conn))
            cmd.ExecuteNonQuery();



    }
         }

         return View(cg);
    }      

View:

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

<table>
<tr> <td> 
    <div class="editor-label">
        @Html.Label("Select old cityname")
    </div> </td>
    <td>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.cityname,@ViewBag.cityname as SelectList,"select")
        @Html.ValidationMessageFor(model => model.cityname)
    </div>

   </td></tr>
<tr> <td> 
    <div class="editor-label">
        @Html.Label("Enter new cityname")
    </div> </td>
    <td>
    <div class="editor-field">
        @Html.EditorFor(model => model.cityname)
        @Html.ValidationMessageFor(model => model.cityname)
    </div>

   </td></tr>
   <tr><td> 
    <p>
        <input type="submit" value="Create" />
    </p>
    </td></tr>

leppie
  • 115,091
  • 17
  • 196
  • 297
user3793029
  • 135
  • 3
  • 13
  • What problem are you having? –  Jan 20 '15 at 06:38
  • You cant use `DropDownListFor()` with the model property and the `ViewBag` property having the same name. And then you have an `EditorFor()` that uses the same property name again (which will just be ignored on postback) –  Jan 20 '15 at 06:41
  • Yep. I don't know how to do this scenario?. Is there any other way to accomplish this task? – user3793029 Jan 20 '15 at 06:44
  • I need both drop down and new text box for the city name in the same view page. – user3793029 Jan 20 '15 at 06:45
  • Your `Create` model needs to have properties for `OldName` and `NewName` so you can post back the values and update the database. –  Jan 20 '15 at 06:46
  • 1
    Additionally, you should *immediately* stop building SQL like that, including values directly within the SQL. Use parameterized SQL, *always*. Otherwise, you have a potential SQL Injection attack. See http://bobby-tables.com – Jon Skeet Jan 20 '15 at 06:50

1 Answers1

1

Create a view model that contains properties for the old and new names

View model

public class CreateVM
{
  [Display(Name = "Old name")]
  [Required]
  public string OldName { get; set; }
  [Display(Name = "New name")]
  [Required]
  public string NewName { get; set; }
  public SelectList CityList { get; set; }
}

Controller

[HttpGet]
public ActionResult Edit(CreateVM model)
{
  CreateVM model = new CreateVM();
  ...
  model.CityList = new SelectList(city, "cityname", "cityname");
  return View(model);
}

[HttpPost]
public ActionResult Edit(CreateVM model)
{
  // the model now contains the selected old name and its new name
}

View

@model CreateVM
@using(Html.BeginForm())
{
  @Html.LabelFor(m => m.OldName)
  @Html.DropDownListFor(m => m.OldName, Model.CityList, "-Please select-")
  @Html.ValidationMessageFor(m => m.OldName)
  @Html.LabelFor(m => m.NewName)
  @Html.TextBoxFor(m => m.NewName)
  @Html.ValidationMessageFor(m => m.NewName)
  <input type="submit" />
}

And as Jon Skeet has noted, use parameterized SQL!

  • Hi Thanks for your response. I am receiving the below error while executing "{"\r\n(138,10) : error 3004: Problem in mapping fragments starting at line 138:No mapping specified for properties Create.citylist, Create.cityList in Set grp.\r\nAn Entity with Key (PK) will not round-trip when:\r\n Entity is type [mvcdemo.Models.Create]\r\n"} – user3793029 Jan 20 '15 at 07:42
  • @user3793029, That error is not related to the code in my answer. Its due to your code for updating the database. Debug you code to determine which line is causing the error. Google "error 3004: Problem in mapping fragments starting at line" to see if you can find a solution, and if not you need to ask a new question. –  Jan 20 '15 at 12:19
  • Hi, I got the solution. I just added new field called newcityname as you mentioned. But i don't want to add newcityname in my table. For now, i added and it works well. Thank you so much for your help. – user3793029 Jan 20 '15 at 12:33
  • You don't need to add the field in your table. I have shown you how to do it with a view model `CreateVM` which is not the same as your data model `Create`. You need to map the properties from you view model to the data model. See [What is a view model in MVC](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Jan 20 '15 at 12:37
  • Its not entirely clear from your question, but I think all you are wanting to do is update an existing city name with a new name, in which case you just want something like `UPDATE tblcity SET cityname = @NewName WHERE cityname = @OldName` and pass the parameters from the view model –  Jan 20 '15 at 12:41