1 . How many repositories is too many?
 

Answer :

It's a few years old now but I've used a UnitOfWork with a GenericRepository and not suffered any major performance issues. This is hooked into over 100 DB tables of a busy website. That said, the website in question also employs the Dapper Micro-ORM throughout as it's very fast and gives more control on complex operations. For CRUD though, the setup below works well for me.

Unit Of Work

public class UnitOfWork :IDisposable
{
    private DbContext _db = new DbContext();

    private GenericRepository<Table1> table1Repository;
    private GenericRepository<Table2> table2Repository;
    private GenericRepository<Table3> table3Repository;
    ...
    private GenericRepository<TableN> tableNRepository;

    public GenericRepository<Table1> Table1Repository
    {
        get
        {
            if (this.table1Repository == null)
            {
                this.table1Repository = new GenericRepository<Table1>(_db);
            }
            return table1Repository;
        }
    }

    public void Save()
    {
        _db.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _db.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

Generic Repository

public class GenericRepository<TEntity> where TEntity :class
{
    internal DbContext _db;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(DbContext _db)
    {
        this._db = _db;
        this.dbSet = _db.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query);
        }
        else
        {
            return query;
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (_db.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        _db.Entry(entityToUpdate).State = EntityState.Modified;
    }

}

Usage

var unitOfWork = new UnitOfWork();

List<Table1> list = unitOfWork.Table1Repository.Get(n => n.addedOn <= DateTime.Now);

Table1 item = unitOfWork.Table1Repository.GetById(1);

unitOfWork.Table1Repository.Insert(object);
unitOfWork.Save();

unitOfWork.Table1Repository.Update(object);
unitOfWork.Save();

unitOfWork.Table1Repository.Delete(1);
unitOfWork.Save();

unitOfWork.Table1Repository.Delete(object);
unitOfWork.Save();

Leave a Comment

Name  
  Email   
Message
1 . MVC Core form tag helper that inherit the current view URL for its action attribute?
 

Answer :

When using HTML helpers, values that are not supplied explicitly default to the route values that are in the current request. That is the reason why you can specify BeginForm with no parameters.

When using tag helpers, this default logic no longer applies - the values must be provided explicitly. There are no defaults.

Option 1 - form tag

The simplest way to mimic what the HTML helper does with a form tag is:

<form action="@Url.RouteUrl(this.ViewContext.RouteData.Values)" method="post">
</form>

Option 2 - Html.BeginForm

Note that your current syntax is also still valid in ASP.NET Core MVC:

@using (Html.BeginForm())
{
}

But since you had to ask this question, I would say that it is absolutely not clear how the URL is being generated when using this syntax, which means you should probably change to using Url.RouteUrl to make it more readable despite being a bit more to write.

Option 3 - Tag Helper

Here is an example of how you could use a tag helper to achieve this, although it is a bit ugly.

There is a form tag helper attribute asp-all-route-values that allows you to pass all of the route values in a single parameter. However, according to asp-all-route-data must be IDictionary<string,object> or RouteValueDictionary, it is not possible to pass a RouteValueDictionary to this attribute, you would need to convert it to an IDictionary<string, string>. One way to do that is to build an extension method to make the conversion.

public static class RouteValueDictionaryExtensions
{
    public static IDictionary<string, string> ToTagHelperValues(this RouteValueDictionary routeValueDictionary)
    {
        var result = new Dictionary<string, string>();
        foreach (var kvp in routeValueDictionary)
        {
            result.Add(kvp.Key, kvp.Value as string);
        }
        return result;
    }
}

You can then use a tag helper to generate the current URL as follows:

<form asp-all-route-data="@this.ViewContext.RouteData.Values.ToTagHelperValues()">
</form>

Option 4 - No action attribute

It is also possible to use a form tag with no action attribute. If you omit the action attribute, the default behavior in most (if not all) browsers is to use the current URL.

<form method="post">
</form>

2 . How do I pass an object from a filter to an action method?
 

Answer :

You are passing the cart to the action using the name cart:

context.ActionArguments["cart"] = _mand;

But when you are accessing it from the action method, the name is mand:

public IActionResult BonEdit(Winkelmand mand, NieuwViewModel model)

In order for it to be passed into the action method, these 2 names must match.

context.ActionArguments["mand"] = _mand;

3 . Having issues with my long running task?
 

Answer :

So what you can do is either optimise your sps and code to perorm second method is instead of loading it via ajax bring the data with the view render function example

now here you should create a new viewmodel and then move but for undrstanding i am using viewbag its not a good practice though

public ActionResult YourAction()
{
ViewBag.TheJsonWhichIsTakingTime = YourBLL.Action();
return view(model);
}

now in the view part

@section scripts
{

$(function(){
var jsonData = @Html.Raw(Json.Encode(ViewBag.TheJsonWhichIsTakingTime));
YourVewRelatedFunction(jsonData);
})

    function YourVewRelatedFunction(data)
    {
    //The Code block you used in success function of ajax
    }

}

4 . Asp net mvc post gives empty viewmodel?

Answer :

You cannot use a foreach loop to generate form controls for collection items and get correct 2-way model binding. You need to use a for loop or and EditorTemplate for typeof CustomerViewModelas explained in Post an HTML Table to ADO.NET DataTable.

In addition, you should avoid binding to a Dictionary because you cannot use the strong typed HtmlHelper method or TagHelpers to give 2-way model binding.

In order oo bind to your current model, your name attribute would need to be in the format name="[#].EmployeeAndHours[Key]" where # is the zero-based collection indexer.

Instead, modify your view models to

public class CustomerViewModel
{
    public string ProjectName { get; set; }
    public List<EmployeeHoursViewMode> EmployeeHours { get; set; }
}
public class EmployeeHoursViewModel
{
    public string Employee { get; set; }
    public int Hours{ get; set; }
}

And the view then becomes

@model List<CustomerViewModel>
<form asp-controller="Customers" .... >
    @for(int i = 0; i < Model.Count i++)
    {
        ....
        <h5>@Model[i].ProjectName</h5>
        @Html.HiddenFor(m => m[i].ProjectName)
        // or <input type="hidden" asp-for-"Model[i].ProjectName />
        <div>
            @for(int j = 0; j < Model[i].EmployeeHours.Count; j++)
            {
                @Html.HiddenFor(m => m[i].EmployeeHours[j].Employee)
                @Html.LabelFor(m => m[i].EmployeeHours[j].Hours, Model[i].EmployeeHours[j].Employee)
                // or <label asp-for="Model[i].EmployeeHours[j].Hours">@Model[i].EmployeeHours[j].Employee</label>
                @Html.TextBoxFor(m => m[i].EmployeeHours[j].Hours, new { type = "range", ... })
                // or <input asp-for-"Model[i].EmployeeHours[j].ProjectName type="range" ... />
            }
        </div>
    }
    <input type="submit" value="Save changes" class="btn btn-success" />
}

Note the above code assumes you want to post back the value of ProjectName (hence the hidden input), and that you want to display the employee name adjacent each 'Hours' input.


5 . Is it possible to create this JSON format using a c# class?
 

Answer :

public class File { public string Url { get; set; } public string Id { get; set; } }

Then create your files like this:

var files = new List<File>();
files.Add(new File{Url = "tmp/abc.jpg", Id = "42"});
files.Add(new File {Url = "tmp/cba.jpg", Id = "24"});

Now you are able to get desired json output with linq query:

var json = JsonConvert.SerializeObject(files.Select((f, i) => new {f, i})
    .ToDictionary(key => $"file-{key.i}", value => value.f));

In my example result would be:

{
  "file-0":{
    "Url":"tmp/abc.jpg",
    "Id":"42"
  },
  "file-1":{
    "Url":"tmp/cba.jpg",
    "Id":"24"
  }
}  


6 . How to get instance of class in Application_BeginRequest?

Answer :

Application_BeginRequest is a legacy ASP.NET classic method that runs outside of the context of MVC. The only way to provide an instance there is to keep an instance of the container around after the Application_Start method runs.

However, MVC has better alternatives. If you have a crosscutting concern that you need to run in each request, you should make a global filter to run that logic.

public class MyFilter : IActionFilter
{
    private readonly ISomeDependency someDependency;

    public MyFilter(ISomeDependency someDependency)
    {
        this.someDependency = someDependency 
            ?? throw new ArgumentNullException(nameof(someDependency));
    }

    // Runs after action method
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    }

    // Runs before action method
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        someDependency.DoSomething();
    }
}

Usage

If you can get away with registering the filter as a singleton, you just need to register it at application startup in the static GlobalFilterCollection.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters, IWindsorContainer container)
    {
        filters.Add(new MyFilter(container.Resolve<ISomeDependency>()));
        filters.Add(new HandleErrorAttribute());
    }
}

If you have dependencies that would be captive (such as DbContext) if you registered as singleton, you can either inject a factory into your filter, or use a custom filter provider to resolve your global filter from the Castle Windsor container.


7 . MVC 5: jQuery nested tabs are not displaying properly?
 

Answer :

This appears to be an issue with nested tabs, possibly because of the way the ajax calls are made and the scripts within your partials (scripts should not be in partials). To make this work, you can provide placeholder elements for the content of each tab and have the links reference those elements using id attributes.

The html would be

<div id="main"> // main (parent) tabs
  <ul>
    <li><a href="#client">Client</a></li>
    <li><a href="#account">Account</a></li>
  </ul>
  <div id="client"> // client tabs
    <ul>
      <li><a href="#client-info">Client Info</a></li>
      <li><a href="#billing-selections">Billing Selections</a></li>
    </ul>
    <div id="client-info">
      // content for client information
    </div>
    <div id="billing-selections">
      // content for billing selections
    </div>
  </div>
  <div id="account"> // account tabs
    <ul>
      <li><a href="#accounts">Accounts</a></li>
    </ul>
    <div id="accounts">
      // content for accounts
    </div>
  </div>
</div>

and to initialize the tabs

$('#main').tabs({ ... }); // set options as required
$('#client').tabs({ ... });
$('#account').tabs({ ... });

To display the content, use @Html.Partial() if the model in the view contains the data need to generate the partial, or @Html.Action() if you want to call a server method that returns the partial. For example, if the Edit() method of ClientSetupController returns the partial view to show in your Client Info tab, then

<div id="client-info">
    @{ Html.RenderAction("Edit", "ClientSetup"); } // or @Html.Action("Edit", "ClientSetup")
</div>

Where the controller method is

[ChildActionOnly]
public PartialViewResult Edit
{
    var model = ... // initialize you model for the view
    return PartialView("_Edit", model);
}

and _Edit.cshtml is a partial view and contains the html you want to display in the tab


8 . Moq won't invoke IAuthenticationManager SignIn method?
 

Answer :

Nkosi said it in a comment to your question:

In the expression

m => m.SignIn(authenticationProperty, identity)

the two arguments authenticationProperty and identity must be "equal" to the two arguments actually passed in (by the System-Under-Test). So does Equals return true when you compare?

You can use It.IsAny<AuthenticationProperties>() or It.Is((AuthenticationProperties x) => x.IsPersistent) or similar, if needed. And analogous for the ClaimsIdentity. Then Moq will no longer require Equals equality.


9 . Can not Call PartialView with Parameter in Mvc [duplicate]?
 

Answer :

 @{ Html.RenderAction("ChildAction","Home", new {param="abc"}):

It invokes the specified child action method and renders the result inline in the parent view.


10 . Bind Json to the DropDownList in MVC 4?
 

Answer :

You can do something like a SelectList

In your controller:

public ActionResult Teams()
{  
    //Covert JSON to .net object using Deserialize method
    var jsonString ="[{\"id\":\"20\",\"name\":\"System Team\"}]";
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    List<Teams> listTeams = (List<Teams>)javaScriptSerializer.Deserialize(jsonString,typeof(List<Teams>));

    var teamList = new List<SelectListItem>();
    foreach (Teams teams in listTeams)
    {
        var listItem = new SelectListItem{ Value = teams.id, Text = teams.name };
        teamList.Add(listItem);
    }

    ViewData["teamList"] = teamList;

}

In your view:

@Html.DropDownList("names", new SelectList((List<SelectListItem>)ViewData["teamList"], "Value", "Text"), "--Select Teams--")

 



11 . How to upload multiple image in asp.net mvc using ajax?
 

Answer :

You can do one thing, take another folder with the name "Temporary". While choosing images through "File Upload" input save them to "Temporary" folder instead of direct saving to main folder & for preview purpose display it from "Temporary" folder. When click on "Upload image" button just copy all files from "Temporary" folder to your main "Destination folder" and make empty "Temporary" folder. While copying images from "Temporary" folder to "Destination Folder" you can perform different operations like change the filename, save image path to DB etc.

Edit :

Here, below is the code snippet, please go through it and let me know for any query:

Step 1: First create 2 folders. One with the name Temp and Second with [Your Destination Folder Name].

Step 2: Create user interface.

<style>
  img {
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 5px;
      width: 150px;
   }
</style>
 <div class="row" style="margin-top:20px;">
    <div class="col-md-6 col-sm-6 col-xs-12">
        <div class="col-md-4" style="margin:0 !important;">
            <label style="margin-top:5px; margin-left: -15px;">
                Select image
            </label>
        </div>
        <div class="col-md-8" style="margin:0 !important;">
            <span class="control-fileupload ">
                <input type="file" id="flImage" name="ImageUpload"
                       onchange='uploadTempImage()' class="form-control">
            </span>
        </div>
    </div>
    <div id="imgPreview"></div>
</div>
<div>
<button id="btnSaveImage" onclick="Upload()">Upload Files</button>
</div>

Step 3: Write a code to make ajax call and to save images.

  function UploadTempImage() {
    var formData = new FormData();
    formData.append('file', $('#flImage')[0].files[0]);
    $.ajax({
        type: 'post',
        url: '/TestImage/SaveToTemp',
        data: formData,
        success: function (response) {
            if (response != null) {
                var my_path = "/temp/" + response;
                var image = '<img src="' + my_path + '" alt="image" style="width:150px">';
                $("#imgPreview").append(image);
            }
        },
        processData: false,
        contentType: false,
        error: function () {
            alert("Whoops something went wrong!");
        }
    });
}

function Upload() {

    $.ajax({
        type: 'get',
        url: '/TestImage/SaveToMainFolder',
        success: function (response) {
            if (response != null) {
                alert(response);
            }
        },

    });
}

Step 4: Write a method to handle ajax request into controller.

    /// <summary>
    /// Save file to Temp folder.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    [ValidateInput(false)]
    public JsonResult SaveToTemp(HttpPostedFileBase file)
    {
        try
        {
            string filename = "";
            string imgepath = "Null";
            if (file != null)
            {
                filename = file.FileName;
                imgepath = filename;
                string extension = Path.GetExtension(file.FileName);
                filename = DateTime.Now.Ticks + filename;
                var path = Path.Combine(Server.MapPath("~/Temp/"), filename);
                file.SaveAs(path);
            }
            return Json(filename, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    /// <summary>
    /// This method is used to move files from Temp folder to Destinatin folder.
    /// </summary>
    /// <returns></returns>
    public JsonResult SaveToMainFolder()
    {

12 . How to fetch data from MongoDB collection in C# using Regular Expression?
 

Answer :

I would recommend storing a normalized version of your data, and index/search upon that. It will likely be considerably faster than using regex. Sure, you'll eat up a little more storage space by including "john" alongside "John", but your data access will be faster since you would just be able to use a standard $eq query.

If you insist on regex, I recommend using ^ (start of line) and $ (end of line) around your search term. Remember though, that you should escape your find value so that its contents isn't treated as RegEx.

This should work:

string escapedFindValue = System.Text.RegularExpressions.Regex.Escape(findValue);
new BsonRegularExpression(string.Format("^{0}$", escapedFindValue), "i");

Or if you're using a newer framework version, you can use string interpolation:

string escapedFindValue = System.Text.RegularExpressions.Regex.Escape(findValue);
new BsonRegularExpression($"^{escapedFindValue}$", "i");

13 . Multiple route configuration does not work for PUT and Delete action in web api?
 

Answer :

Converting to an answer.

I think the ActionNameAtrribute you are using is from MVC, not web api, so remove it, it wont do anything in this case.

Here is what I believe should work for you:

[HttpGet]
public HttpResponseMessage Get()
{
    _lst = new List<int>() { 1, 2, 3, 4, 5 };
    return ToJson(_lst);
}

[HttpPost]
public HttpResponseMessage Post(int id)
{
    _lst.Add(id);
    return ToJson(1);
}

[HttpPut]
public HttpResponseMessage Put(int id)
{
    //doing sothing
    return ToJson(1);
}

[HttpDelete]
public HttpResponseMessage Delete(int id)
{
    //doing sothing
    return ToJson(1);
}

[HttpPost, Route("~/api/tests/save/{id}")]
public HttpResponseMessage Save(int id)
{
    //doing sothing
    return ToJson(1);
}

webapiconfig.cs:

 config.MapHttpAttributeRoutes();

 config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    name: "DefaultApiWithAction",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

The following patterns should now work, note that I've amended your first post call as the parameter id is present.

POST -> http://localhost:56114/api/Test/1   -> should call Post
GET -> http://localhost:56114/api/Test/    -> should call Get
PUT -> http://localhost:56114/api/Test/3   -> should call Put 
DELETE -> http://localhost:56114/api/Test/4  -> should call Delete
POST -> http://localhost:56114/api/Test/Save/1  -> should call Save

Your default routing is still applied as well as the more specific api/{controller}/{action}/{id}rout


14 . MVC Razor - Serialize HTML elements to C# collection?
 

Answer :

I believe you will get the correct ID's and names if you use the HTML helpers. Also you have to use array instead of collection:

 public FamilyMember[] FamilyMembers { get; set; }

@for (int i = 0; i < Model.FamilyMembers.Length; i++) { 
        <li class="family-member">
          @Html.TextBoxFor(m => Model.FamilyMembers[i].FirstName, new {style = "display:none;"})
        </li>
      }

This would result in code:

<input id="FamilyMembers_0__FirstName" name="FamilyMembers[0].FirstName" style="display:none;" type="text" value="Name0">

Witch would result in this serialized value: FamilyMembers%5B0%5D.FirstName=Name0&FamilyMembers%5B1%5D.FirstName=Name1&FamilyMembers%5B2%5D.FirstName=Name2

Also this might be better serialized as json using serializeArray, have a look at this question: Convert form data to JavaScript object with jQuery

EDIT: here is how you could do it with serializeArray and keep using iCollection

First you need to set the name correctly.

 @{ var i = -1;}
    <ul class="family-list small-text" id="family-list">
      @foreach (var familyMembers in Model.FamilyMembers)
      {
        i++;
        <li class="family-member">
          @Html.TextBoxFor(m => familyMembers.Age, new {Name = "familyMembers[" + i + "].Age", style="display:none;" })
        </li>
      }
    </ul>

Then you need to serialize this as JSON, and post it as JSON

function objectifyForm(formArray) {//serialize data function
  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }
  return returnArray;
}
var data = objectifyForm($('form').serializeArray());
$.ajax({
  data: data,
  dataType: "text/json",
  type: "POST",
  url: "/api/savetransferee",
  success: success,
  error: error
});

15 . View data from database using MVC & Entity Framework?
 

Answer :

ViewBag.itemOutput is a List<string> which makes item a string.

Therefore, use @item instead of @item.name (as string does not have .name property) in your view:

@foreach (var item in ViewBag.itemOutput )
{
    <table id="t01">
        <tr>
            <td>@item</td>
        </tr>
    </table>
}

Also, to get the full list, you could do:

public List<string> getListOfItems()
{
    return (from x in db.Items select x.Text).ToList();
}

And then just call getListOfItems() with no param.


Random comments:

1) Don't use plural for class name, unless the class is somewhat a collection of things

--> public class item // without s

2) You said in comments that items are full varchar which is untrue as per your class definition (you have IDname & quantity).

3) Using string for quantity is a bit weird.

4) You could indeed change your getListOfItems method to:

public List<item> getListOfItems()
{
    return (from x in db.Items select x).ToList();
    // which can be simplified to:
    // return db.Items.ToList();
}

but you should then change your view back to @item.name.

This would however allow you to do:

@foreach (var item in ViewBag.itemOutput )
{
    <table id="t01">
        <tr>
            <td>@item.name</td>
            <td>@item.quantity</td>
        </tr>
    </table>
}

5) You have an ItemModel but you are not using it. You could modify it and use it instead of the ViewBag.