Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, June 8, 2017

MVC Caching issue

Issue:

I had an issue with a MVC view rendering a modal page.  The problem was that the AJAX call was not refreshing the view when it was re-rendered on the page.  The change to the database is occurring but the view refresh was not showing the latest information.

 var data = { "claimNumber": activeClaimID };
        $.ajax
        (
                 {
                     url: '@Url.Action("IndexPartial", "CaseFileViewModels")',
                     async: false,
                     type: 'GET',
                     data: data,
                     success: function (result) {

                         hideWaitDialog();
                       
                         //Clear out the entire modal block
                         $('#modal-container').empty();
                         $('#modal-container').append(result);
                         ret = true;
                     },
                     error: function (xhr, status, err) {
                         alert(xhr.responseText);
                         alert(status);
                     },
                 }
         );


My problem was that I did not assign the attribute Output Cache to the ActionResult.
Once I disabled the default hander on ActionResult then my view began to refresh.

[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult IndexPartial()
{....}


Source:

https://stackoverflow.com/questions/20917398/view-not-refreshing-after-ajax-call


Friday, April 14, 2017

Set variable formatting in MVC razor

Issue

This was a real challenge to figure out.  It seems pretty straight forward but it is the details that eat up so much time.  I had a number of decimal data types that represented currency.  I wanted them displayed at local currency.  I thought .Net has this down and lots of people have done this already.  Easy, right?

Well, yes and no.  I went to implement and found most examples and answers incomplete.

Here is what you need.  In the razor view, add references to the threading and globalization namespaces:

@using System.Threading
@using System.Globalization

In your markup, use the String.Format and CultureInfo methods to get your formatting correct.

 var tDebit = String.Format(new CultureInfo("en-US"), "{0:C}", nDebit);
 @Html.Raw(tDebit);



Sources

  1. https://msdn.microsoft.com/en-us/library/bz9tc508.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-3
  2. http://stackoverflow.com/questions/10740828/format-decimal-to-currency-in-viewbag
  3. https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Wednesday, March 22, 2017

MVC attribute DataFormatString

Issue

Needed to format dates in an MVC model.  I wanted to use the attribute decorators for the properties.
I just could not remember the syntax for DataFormatString

  [Display(Name = "Date Notified")]
  [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy} ")]
  public DateTime? Received_Date { get; set; }

{0:dd MMMM yyyy}    -    gives 24 February 2006
{0:MMM dd}    -    gives Feb 24 (substitue MMM with MMMM for the full month name instead of abbreviation)
{0:dd/MM/yy}    -    gives 24/02/06
{0:dd/MM/yyyy}    -    gives 24/02/2006


Source

https://social.msdn.microsoft.com/Forums/windows/en-US/bb8b1e0e-bd41-4206-9895-4e79463b9bc6/dataformatstring-for-datetime-column?forum=winformsdatacontrols

Monday, March 20, 2017

Remove Timestamp from a DateTime variable in MVC Razor

Issue

I needed to format some dates on a View and could not remember the syntax.

Define in your model a readonly variable

public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }
Then in the razor syntax just use DisplayFor

DisplayFor(modelItem => item.startDateFormatted)

OR

You can use the assign the date formatting attributes on the property of the model

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }

Source

http://stackoverflow.com/questions/11122171/asp-net-mvc-razor-remove-time-from-datetime-property

Friday, March 17, 2017

AJAX Controller Action Method from a Razor View


Issue

How to call to a controller action from jquery?

Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}
Person class
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
Key to note here is that the data line id must match the name of the variable in the Action result parameter list.

Source

http://stackoverflow.com/questions/14049817/in-asp-net-mvc-all-possible-ways-to-call-controller-action-method-from-a-razor
http://stackoverflow.com/questions/1194104/jquery-ajax-ajax-passing-parameters-to-callback-good-pattern-to-use
http://stackoverflow.com/questions/15576548/how-to-pass-parameters-in-get-requests-with-jquery

Tuesday, July 5, 2016

MVC 5 Razor - Compilation Error CS0246 - Type or namespace could not be found


Problem:

I ran across this issue in a vs 13 project. I was running in my dev environment with a project I had reused. The project was building and running until I removed the web service reference. I followed the prescribed method in MSDN (see reference). Then each time I built the project it compiled. However, each debug session resulted in a runtime error.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS0246: The type or namespace name 'ExpiredNamespace' could not be found (are you missing a using directive or an assembly reference?)





Solution:

I was absolutely puzzled by the error since I had removed all references to the namespace ExpiredNamespace from the project.  It was not reference anywhere.  If I was missing a reference then I should be seeing a compiler error. 


Then I began looking at the trace information and read up on the MVC razor process.  That is when I found my rogue reference.  The error always occurred when the View attempted to run.  I spared a look at the web.config.


<pages pageBaseType="System.Web.Mvc.WebViewPage">

<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="ExpiredNamespace'" />
</namespaces>

</pages>


The base page type renders the on run compilation using these classes.  I had inadvertently carried over the reference in the web.config from my old project!


Note to self, scrub your test projects carefully before reusing them.






Reference:

https://msdn.microsoft.com/en-us/library/d9w023sx.aspx

Tuesday, May 24, 2016

Call stored procedure in MVC

Problem:

Migrating an application with existing database into MVC 5.  Things are going great with EF model but have some reports written as stored procedures and needed a way to call them in the new design.




Solution:

The key is to call sproc using the datacontext from your model.  This can then be put in the controller and the result set is passed out to a viewmodel object which you define in your project.  The view is then run against the view model to display the results.




Controller



var spParameters = new object[5];


spParameters[0] = new SqlParameter()
{
 ParameterName = "office_IDs",
 Value = OfficeIds
};


spParameters[1] = new SqlParameter()
{
 ParameterName = "country",
 Value = country
};

spParameters[2] = new SqlParameter()
{
 ParameterName = "branchofservice",
Value = service
};
spParameters[3] = new SqlParameter()
{
ParameterName = "dateBegin",
Value = dateBegin
};
spParameters[4] = new SqlParameter()
{
ParameterName = "dateEnd",
Value = dateEnd
};

DbContext context = new DbContext("ModelContext");


var datalist = context.Database.SqlQuery<OtherOffenseItemizationModelView>("exec dbo.getOtherOffenseItemization @office_IDs,@country,@branchOfService,@dateBegin,@dateEnd", spParameters).ToList();



return View(datalist);




View


@model IEnumerable<FCJC.ModelView.OtherOffenseItemizationModelView>
<div>
    <table class="table table-striped">
        <tr>
            <th colspan="5" class="text-center table-bordered">
      TITLE
            </th>
        </tr>
        <tr class="alert-info table-bordered">
            <th>
                @Html.DisplayNameFor(model => model.OffenseOther)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MIL)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CIV)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DEP)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TOTAL)
            </th>
           
        </tr>
        @foreach (var item in Model)
        {
            <tr class="table-bordered">
                <td>
                    @Html.DisplayFor(modelItem => item.OffenseOther)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.MIL)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CIV)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DEP)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.TOTAL)
                </td>
            </tr>
        }
    </table>

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

Friday, March 18, 2016

wif10201: No valid key mapping found for securityToken: 'System.IdentityModel.Tokens.X509SecurityToken' and issuer: 'http://login.eur.army.mil/adfs/services/trust'.

There are might be 2 cases for this error.
  1. Get the actual thumbprint from ADFS and put in web.config thumbprint tag
  2. mismatch in port number (running application port number and port number which is configured in ADFS)
First option was my issue.  I changed the thumbprint and the issue was resolved.


Source:
http://stackoverflow.com/questions/24304097/no-valid-key-mapping-found-for-securitytoken

Wednesday, February 24, 2016

Attempted to access an unloaded appdomain. (Exception from HRESULT: 0x80131014)

Problem:

Using MVC 5 application and the namespace System.DirectoryServices.AccountManagement.
I kept getting this error intermittently running my app.  Looks like an issue in ADSI which is a bit buggy. 

Solution:

Tofumaster's suggestion of adding the domain string to the principal context seems to have done the trick for me. 

instead of

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

do this

PrincipalContext ctx = new PrincipalContext(ContextType.Domain,"MyDomain");



Source:

  1. http://stackoverflow.com/questions/6605666/querying-active-directory-from-mvc-result-in-attempted-to-access-an-unloaded-ap
  2. http://forums.asp.net/t/1697428.aspx?Querying+Active+Directory+from+MVC+result+in+Attempted+to+access+an+unloaded+appdomain+Exception+from+HRESULT+0x80131014+
  3. http://stackoverflow.com/questions/5895128/attempted-to-access-an-unloaded-appdomain-when-using-system-directoryservices