Archive for March, 2016

MVC – Setting focus on a control

To set focus on a control when an MVC view loads, use the following syntax to attach the “autofocus” tag to the HTML element:

@Html.TextBox("Last", null, new { autofocus = "" })

,

Leave a comment

Download your deployed application from Azure

Need to download the web application and files you deployed into Azure? Bring up the Azure portal. I’m using the “new” version (it’s been out for years now, but I still consider it the new one). Then, select your application to bring up the properties. From the list of actions, select “Get publish profile”:

Azure publish settings

Azure publish settings

Open the publish profile file and you’ll see all kinds of wonderful XML. There are a couple of <publishprofile> elements inside. Look for one that defines the FTP publishing information, like this:

<publishProfile profileName=”MyApp – FTP”

Find the userName and userPWD settings under the FTP profile section – they are located right after the “ftpPassiveMode” setting is declared. Just plug in your username and password into your favorite FTP client, and away you go!

Leave a comment

An exception of type ‘System.TypeInitializationException’ occurred

I was running code that called a static class, Repository, to populate an Application variable, like so:

Application["UserTypes"] = Repository.PopulateUserTypes();

When I did this, I received the following error:

 An exception of type 'System.TypeInitializationException' occurred in ScottApp.dll but was not handled in user code

The InnerException property was not terribly helpful:

Object reference not set to an instance of an object.

Turns out it was because I had forgotten to add a connection string, “ScottConn”, to the web.config. The static Repository class was attempting to reference this missing property when it loaded:

private static string connString = ConfigurationManager.ConnectionStrings["ScottConn"].ConnectionString;

Adding this missing string to the web.config file, the error disappeared.

Leave a comment

ORA-01008: not all variables bound

This was one of those “duh” error. I was attempting to retrieve data from Oracle using some simple ADO.NET code, like the code below, but I was receiving the error “ORA-01008: not all variables bound“.

string value = String.Empty;
using (OracleConnection conn = new OracleConnection(connString)) {
    using (OracleCommand comm = new OracleCommand("SELECT Description FROM ScottsTable WHERE ID = :id", conn)) {
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add(":id", OracleDbType.Varchar2, 40).Value = "scott";
        conn.Open();
        value = comm.ExecuteScalar().ToString();
    }
}

The problem was I was setting the OracleCommand’s CommandType property to StoredProcedure when it was actually straight text. Removing this line resolved the error.

 

Leave a comment

Call Index action after a POST with MVC

I had a page with a list of records that the user could view to see what was in the queue of things to do. The user would click on the link to bring up a table where they could choose which record to edit.


Choosing this record would populate the view with the fields. The user could then update the values, click “Save” to generate a POST request, and then return back to the Index view.

The problem was that my redirect to the Index view, while returning to the right view, wasn’t showing the link with the remaining records. Here is how I was attempting to do this:

return View("Index", item);

To fix this, I made a call to “RedirectToAction” to call the controller’s Index action:

return RedirectToAction("Index", "MyController", item);

The fields were cleared just as I wanted (because I had set the model to null before passing into “RedirectToAction”) and the remaining records link was there as expected.

Leave a comment

Deleting a row from inside a partial view

Post #200! I hope it’s a good one…

I had a view, within which was a partial view that contained a table. Inside this table was link to delete the current table row.

Form

Form

So to recap: View -> Partial View -> Delete Row

Since I did not want the whole page to refresh, I needed to use some jQuery to do this.
On my main page, I populated the various drop down lists you see above. Leaving out all that code, I have this remaining code at the bottom of the page:

    function deleteRow(id) {
        $.ajax({
            url: "/MyApp/DeletePermission",
            type: "GET",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("#results").html(partialViewResult);
        });
    }

The “results” DIV tag holds the partial view, which I am populating with an onchange event earlier in the page. I assume you have this part down, but if not, post a comment and I’ll write something up about binding data to a partial view. Heck, maybe I will anyways.

In my partial view, I build the table, a truncated version of which is here:

     @foreach (var item in Model) {
         <tr>
             <td>@Html.DisplayFor(modelItem => item.) </td>
             <td><a onclick="deleteRow('@item.ID')">Delete</a></td>
         </tr>
     }

So when I click the “Delete” link in the partial view, it will call the “deleteRow” function in the main view. The jQuery will then call my controller action:

  public ActionResult DeletePermission(Permission item) {
      List<Permission> model = Repository.DeletePermission(item.ID);
      return PartialView("_PermissionsTable", model);
  }

Notice that the action returns a list of Permission objects, which is then use to refresh / rebind the table when the “done” method of the jQuery function is completed.

,

Leave a comment

Keeping a DropDownList value across a post request in MVC

Who hasn’t, as least once in their lives, needed to persist the value of a DropDownList after a POST request in MVC? No one, that’s who. So here we go.

I first populate a List of SelectListItems in my Repository:

        public static List<SelectListItem> PopulateUsers() {
            List<SelectListItem> items = new List<SelectListItem>();
            // yada yada yada
            return items;
        }

In my case, I wanted to store the items in a Cache variable:

        private void PopulateCacheVariables() {
            if (HttpRuntime.Cache["Users"] == null) {
                HttpRuntime.Cache.Insert("Users", Repository.PopulateUsers(), null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 8, 0, 0));
            }
        }

In the GET request in the controller that returns my view, I create a SelectList that holds my wonderful list of items:

        public ActionResult ManageUsers() {
            PopulateCacheVariables();
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text");
            return View();
        }

In my view, I create a DropDownList and populate using my ViewBag variable:

@Html.DropDownList("User", (SelectList)ViewBag.Users, "--Select User--", new { @class = "form-control" })

Finally, the good part. I perform some validation (not all shown here) to make sure that the required fields are provided. If they are not, then I tell the ModelState to become invalid. If the ModelState.IsValid check is false, the “else” section executes. In this section, I create the SelectList using an extra parameter, the currently selected user, to persist that value when the view is returned.

If all the required fields were selected, then the process completes successfully and the SelectList is generated with no extra parameter so the value is not persisted and the field resets to its default value.

    [HttpPost]
    public ActionResult ManageUsers(TheUser model) {
       if (!String.IsNotNullOrEmpty(Request["Application"])) {
           ModelState.AddModelError("Application", "Application is required");
       }
       if (ModelState.IsValid) {
            AppHubRepository.CreateUser(Request["User"], Request["Application"]);
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text");
        } else {
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text", Request["User"]);
        }
        return View(model);
    }

 

Leave a comment