Tuesday, March 21, 2017

Set an Html.RadioButtonFor() helper as default Checked

Good day!
Given that you have to set a radio button as default checked in razor view, a code to do that is presented below using conditional ternary operator. However, there is an issue with the code shown below. Even if you set the checked property with empty string, it will still render as checked during run-time.
@foreach (var answer in item.Answers)
{
 <p>
  @Html.RadioButtonFor(m => answer.ID, true,
     new
     {
      @disabled = "true",
      @Name = item.ID,
      @checked = (answer.IsCorrect) ? "checked" : ""
     })@answer.AnswerText
 </p>
}           
To ignore that issue, there are several ways to fix that. First one is to use if statement in the view itself.
@foreach (var answer in item.Answers)
{
 <p>
  @if (answer.IsCorrectAnswer)
  {
   @Html.RadioButtonFor(m => answer.ID, true,
     new
     {
      @disabled = "true",
      @Name = item.ID,
      @checked = "true"
     })@answer.AnswerText

  }
  else
  {

   @Html.RadioButtonFor(m => answer.ID, false,
     new
     {
      @disabled = "true",
      @Name = item.ID,
     })@answer.AnswerText
  }
 </p>
}
And another one is to create a custom RadioButton helper.
public static MvcHtmlString RadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, 
 Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes, bool checkedState)
{
 var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

 TagBuilder tagbuilder = new TagBuilder("input");
 tagbuilder.Attributes.Add("value", value.ToString());
 tagbuilder.Attributes.Add("type", "radio");
 tagbuilder.Attributes.Add("id", ExpressionHelper.GetExpressionText(expression));

 if (checkedState)
 {
  tagbuilder.Attributes.Add("checked", "checked");
 }

 foreach (var item in htmlAttributeDictionary)
 {
  tagbuilder.Attributes.Add(item.Key, item.Value.ToString());
 }

 return MvcHtmlString.Create(tagbuilder.ToString(TagRenderMode.Normal));
}
Usage of custom HtmlHelper
@Html.RadioButtonFor(m => answer.ID, (answer.IsCorrectAnswer) ? true : false, new
{
 @disabled = "true",
 @Name = String.Format("Question_{0}", item.ID),
}, answer.IsCorrectAnswer)@answer.Text

Cheers! :-)

Friday, March 17, 2017

Handle GridView TemplateFields null values in aspx markup

Hello,
To handle null values in GridView TemplateFields through aspx/html markup rather than code-behind, you can simply use the language operators to those fields. One approach is to use the conditional ternary operator in C# and VB.NET. The sample codes below illustrates how to do in C# and VB.NET. For C#, use the (?) operator. While VB.NET uses If() operator.
C#.NET Code
 <asp:TemplateField HeaderText="Name" SortExpression="EmpName">
 <ItemTemplate>
    <asp:Label ID="lbl" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:TextBox ID="txtEmployee" runat="server" Text='<%# Eval("EmpName") == System.DBNull.Value ? string.Empty : Eval("EmpName").ToString() %>' ></asp:TextBox>
 </EditItemTemplate>
</asp:TemplateField>
    
VB.NET Code
<asp:TemplateField HeaderText="Name" SortExpression="EmpName">
 <ItemTemplate>
    <asp:Label ID="lbl" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:TextBox ID="txtEmployee" runat="server" Text='<%# If(IsDBNull(Eval("EmpName")), String.Empty, Eval("EmpName").ToString())%>' ></asp:TextBox>
 </EditItemTemplate>
</asp:TemplateField>

Cheers! :-)

Sunday, March 12, 2017

View in ASP.NET MVC not refreshing after calling Ajax Post in jQuery UI

Hello,
In an application wherein the controller is invoked using Ajax POST and that controller will redirect to a landing page such as Index after processing, an issue will occur such as the View of that landing page isn't updated or not refreshed. Normally, the View will be updated since the model is queried from the database.
[HttpPost]
public ActionResult Delete(int id)
{
 try
 {
  Customer customer = _customer.Customers.FirstOrDefault(t => t.CustomerID == id);
  if (customer != null)
  {
   _customer.Customers.Remove(customer);
   _customer.SaveChanges();
  }
 }
 catch
 {
  //TODO
 }

 return RedirectToAction("Index");
}
The fix for that is to change the RedirectToAction() statement to return the url of a landing page as JSON result. And in the ajax statement, add a statement that navigate to the url returned from the controller.
[HttpPost]
public ActionResult Delete(int id)
{
 try
 {
  Customer customer = _customer.Customers.FirstOrDefault(t => t.CustomerID == id);
  if (customer != null)
  {
   _customer.Customers.Remove(customer);
   _customer.SaveChanges();
  }
 }
 catch
 {
  //TODO
 }

 var url = this.Url.Action("Index", "Customer", null, Request.Url.Scheme);
 return Json(new { Url = url });
}
JavaScript Code:
$.post(url,"", function (data) {
 alert('Record successfully deleted from database!');
 window.location.href = data.Url
});
See related issue here: Return View() statement not redirecting to View in ASP.NET MVC using $.ajax() post.

Saturday, March 11, 2017

Url Variable Returns Forward Slash "/" instead of absolute Url in Controller Action

Hi,
When passing a url from a controller action to an Ajax $.post() result that is to navigate to the landing page, using the code below generates only a forward slash which is the root symbol instead of an absolute url. If the url value (/) will be used in window.location.href, it will cause an IIS page not found error.
var url = new UrlHelper(Request.RequestContext).Action("Index", "Customer");
return Json(new { Url = url });
So, to return the absolute url of the controller action in the current context, replace UrlHelper class with Url.Action() method. It is important to include the Request.Url.Scheme in the parameter to pass the correct protocol of the url. The code below will return an absolute url such as: http://localhost:7088 for the landing page.
var url = this.Url.Action("Index", "Customer", null, Request.Url.Scheme);
return Json(new { Url = url });

Wednesday, March 1, 2017

window.location.href not opening website

Hello,
The code below does not open the link, instead opens a blank page or IIS error. This issue occurs in all major browsers.
window.location.href  = 'www.nba.com';
In order to fix the issue,you must prepend the correct protocol before the website such as (http:// or https:// or ftp://). If the protocol is omitted, the link is interpreted as a file in the website.
window.location.href ='http://www.nba.com'; 

Cheers!