How to design the page for model List Binding - c#

I have around 20 cities in my database. I need to develop a page where I can allocation some value to each city. I can update the allocation in the page.
My Data base looks like below
City table - > City(CityId, Name)
I have a table to store the allocation for cities
Table - > CityAllocation(CityId, Allocation)
I have to display a text box near all the city names.
CityAllocationViewModel.cs
public class CityAllocationViewModel
{
public List<City> Cities{get;set;}
public List<CityAllocation> CityAllocations{get;set;}
}
CityAllocation.cshtml
Step 1: To display all the cities I will loop through Cities list and display it.
Step 2: Need to display text boxes near each of the city -> which will load existing values from CityAllocations if anything is there. Otherwise just need to display empty
But for the first time CityAllocations list will be null. Can someone explain me how to construct text box with proper binding name so that when I save it, the values gets properly binded to action method parameter. I am using MVC 4.
My Action method looks like below
CityController.cs
public ActionResult SaveCityAllocation(CityAllocationViewModel cityAllocationViewModel)
{
}

I will suggest use EditorTemplateFor . Create a partial View for CityAllocation and call in main view CityAllocationViewModel with as #html.EditorFor(m=>m.CityAllocations)

Related

Handling Like and Unlike of an entity in ASP.NET MVC using AJAX

I have a razor view where the model is an IEnumerable of Product so I am simply listing all of the products in the view using a foreach loop on the Model. Along with each product you can see below that I am showing the count of how many ThumbsUps it has. The final thing I am trying to accomplish is when they click on the link 'Give Thumbs Up' I would like to add a ProductThumbsUp record to the database for the current logged in user. If the user already has given a thumbs up and clicks it again I would like to remove their ProductThumbsUp from the product.
I am using EntityFramework 7 and MVC6. I have two tables: Product and ProductThumbsUp.
I would like to know how I should go about adding a ProductThumbsUp record for the current logged in user when they click the link using MVC. I am assuming something like this should definitely be an AJAX post. But would I simply just want to send the ProductId to the AJAX post? Then in my controller create a new ProductThumbsUp and set the ProductId of it. Then send both the newly created ProductThumbsUp object and the current logged in user down to my repository layer for saving.
I am wondering if there are better ways to do this since each post in my model already has a list of ThumbsUps attached to it. Is there a better way I can be doing this?
Here is how my razor view is setup:
#model IEnumerable<Product>
#foreach (var product in Model)
{
<h2>#product.Name</h2>
<div>#product.Description</div>
# of Thumbs Ups Given:<span class="badge">#product.ThumbsUps.Count()</span>
Give Thumbs Up
}
Here is what my Product model looks like:
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<ProductThumbsUp> ThumbsUps { get; set; }
To make it efficient,
I would recommend getting all the products and instead of getting all the rows of thumbsUps for each product from DB, just get the like count for each product.
As you dont need each row of thumbsUp but just the count to display. Imagine the scenario for scale if you have a million likes on a product, suddenly you are pulling a million rows from the DB to your server - just to show a count.
Also i would make a second call to the database to get all the thumbsUps the current user has given (a list of product Ids he has liked). That will allow you to display to the user if they have liked it or now.
To add the acutal thumbs up to the product - you can send an ajax call which tells which productId he liked and mvc action can insert a thumbsUp row to the database.
Easiest way to do it is Create Two anchor tags
Give Thumbs Up
Remove Thumbs Up
And toggle it using javascript or jquery.
Similarly call method using jquery ajax to add and remove the count(can use the same method using a flag)
Using the same method you can return the new Count and bind it

Creating a new form - Sharepoint

So I have the code as such:
private void newAddFormForMembers(SPList list, SPWeb web)
{
list = web.Lists["MemberRecords"];
string url = string.Format("_layouts/createform.apsx", web.ServerRelativeUrl, list.RootFolder.Url);
var form = web.GetFile(url);
if (form != null)
{
list.DefaultNewFormUrl = url;
list.Update();
}
}
I have used SharePoint 2010 designer to go and grab the existing html for the creatform form when adding items to a particular list. I added in two new fields, first and last name. The list contains a member name, I removed this field from the create form because:
When I hit submit to add the item to the list, first and last name need to format them selves into "lastname, first name". Now I could submit the form back to my self - How do I do that? - and then do my string manipulation How do i get the values form a field? - and then push the information to the list How do I do that? but then I have anew issue
Edit will look the exact same as add, first and last name fields, how would I take the information from the list and populate the new edit form, particularly first and last name fields, keeping in mind that in the list they are in the format of "lastname, firstname"?
This is all being done programatically
Instead of change html newForm for the list try to write an Event Receiver
Instead of delete field from the newForm try to hide columns (You can do that programmatically or using external tool such as Sharepoint Manager
Adding fields to the new/edit form and grab value on postback event I think is not simple/possible (via javascript you can access onPreSave where you can manipulate item values before postback, here you can write some jscript for save values into field but on edit is hard to split values).
You can: create two column on your list FirstName and LastName, plus a third field FullName (hidden for new/edit form) and with an EH on Added/Updated you can write FullName = LastName + ", " + FirstName or without EH you can create a calculated Field.

Article/news ordering by order id

I m having a little trouble coming up with a schema to order and changing order in a article/news management system.
Here goes:
I have News Object Model as follow:
class News {
int id;
string Title;
string Content;
string OrderId;
// trimmed
}
I have CRUD for the object model. and List as follows:
Id Title Order
1. Foo -+
2. Bar -+
3. Glah -+
What i want to do is when user clicks on - for first news, i want to replace 1 and 2 orderid and of course display as well.
well how do i do this on server side? lets say for 1. item order id is 1 , how do i find the first item that has a higher order id then this one?
Or take 2. Bar, when i click on - , how do i find/replace order ids with first one. or i click on + how do i replace order id of this news with 3. Glah ?
is there a better way of doing this?
There are also some UI where user drags and drops ? any pointers on that?
When the user changes the location of an item, the server needs to know which item was changed and what it's new position is. In the code below, I'm using a List to figure out the new positons. In this sample code, newPosition is the new zero-based position and selectedArticle is the article that was moved.
List<Article> articles = LoadSortedArticles()
articles.Remove(selectedArticle);
articles.Insert(newPosition, selectedArticle);
UpdateArticles(articles);
After running, the article's index within the list tells you its new position. That applies to all articles in the list and works the same for a drag/drop UI. I don't know entity framework, but if you can map the orderId field in the database to the index of the article in the list, then you should be good to go.
I hope this is at least able to give you some ideas. Maybe someone else can give a solution specific to entity framework, but I think putting the articles into a sorted list and letting the list do the work might be the easiest way.
I think the best approach here would be to implement a Swap method that takes two News objects and swaps their OrderId, which I am assuming is numeric.
So the idea would be that you would pass this method the object that was clicked on, as well as either the one above (if the user clicked +) or the one below (if they clicked -). If you do it this way then you avoid the task of trying to find the next or previous item.
In the case of drag and drop, the task is a little different. You would first need to retrieve all the items between (and including) the item being dragged and the drop target, ordered by OrderId. From there you swap the dragged item with the next or previous item (depending on direction), and continue doing so until you have swapped it with the drop target.

search a list MVC3

I am having an issue with search/filter.
I have a list (user details - pic,name) and I use html helper editorformodel to display the list, I would like to incorporate search for the list, as I type in each letter I would like the list to display the matching items from the list without going back to controller. Is this possible?
I have seen some posts like Asp.Net MVC3 adding search functionality but they go back to controller
I am new to MVC, Please help.
Indira
Edit(additional info):
Here's what I was doing, I am passing a model(there are two lists and two strings) from controller to view, using Editorformodel() in view and creating partialview for model. In the partialview I display two lists( which in turn are models containing name,picture url ,bool value). I need to search through this list for matching string from the username's as we type in letters, and select those elements to pass to the model.
Example:
public class myuser
{string name;string picture_url; bool selected;}
public class mylibrary
{string name; IEnumerable<myuser> userlist; IEnumerable<myuser> adminuser; string deadline;}
controller{...... return view(mylibrary);}
In the model
#model ....models.mylibrary
.
.
.
#using(Html.BeginForm(....)
{
#Html.EditorForModel()
}
Partial view for mylibrary
#model ....models.mylibrary
#Html.EditorFor(x=>x.userlist) ---this is the list I want to search through
#Html.EditorFor(x=>x.adminuser)
#Html.TextBoxFor(x=>x.deadline)
partial view for myuser
#model .....models.myuser
#html.Checkboxfor(x=>x.selected)
#html.LabelFor(x=>x.Name)
I am not using any table to display, it's all html. I'd like to modify the list on every keystroke and return the updated list and that's were I'm struggling. Please let me know if you need more detail, and thanks again for the help.
Select To Autocomplete is a good jQuery plugin for achieving this functionality. It requires only a single line to turn a select list into an autocompletable input
$('select').selectToAutocomplete();

Getting more than one item from a database in ASP .NET MVC 3

I'm creating a database where users can enter some Error Reports and we can view them. I'm making these database with C# in the ASP MVC 3 .NET framework (as the tags imply). Each Error Report has a unique ID, dubbed ReportId, thus none of them are stored under the same Id. However, whenever a User creates a new Error, I pass their User Name and store it in with the rest of the report (I use User.Identity.Name.ToString() to get their name and store it as a string). I know how to get a single item from the data using a lambda expression, like so:
db.DBSetName.Single(g => g.Name == genre)
The above code is based on an MVC 3 tutorial (The Movie Store one) provided by ASP. This was how they taught me how to do it.
My major question is: is there a member function like the .Single one that will parse through the whole database and only output database entries whose stored User Name matches that of the currently logged in user's? Then, I can use this to restrict User's to being only able to edit their own entries, since only their entries would be passed to the User's View.
What would be the best way to implement this? Since the ReportId will not be changed, a new data structure can be created to store the user's Errors and passed through to the Index (or Home) View of that particular controller. From there they should be able to click any edit link, which will pass the stored ReportId back to the Edit Action of this particular controller, which can then search the entire database for it. Am I right in assuming this would work? And would this be ideal, given that the other items in the database are NOT passed through to the Index in this method, meaning the User does not have access to the other items' ReportId's, which the user needs to pass into the Edit Action for it to work? If this is ideal, this is the method that requires me to know how to parse through a database and grab every element that fits a particular description (stored User Name matches User's current User Name).
Or would a better approach be to pass the whole database to the Index View and only output the database entries that have User Name values that match the current logged in user's? I guess this could be done in a foreach loop with a nested if loop, like so:
#foreach(var item in db.Reports)
{
if(item.UserName == User.Identity.Name.ToString())
{
...code to output table...
}
}
But this passes the whole database which gives the user a lot more info than they need. It also gives them potential access to info I don't want them to have. However, I don't have to make a new data structure or database, which should lower server memory usage and fetch time, right? Or are databases passed by copy? If so, this method seems kinda dumb. However, I don't know if the first method would fracture the database potentially, this one certainly would not. Also don't remember if I NEED an else statement in C#, I'm more familiar with C++, where you don't need one and you also don't need {}'s for single line if's, if I need one: please don't judge me too harshly on it!
Small note: I am using CRUD Controllers made with the Entity First Framework in order to edit my database. As such, all creation, reading, updating, and deletion code has been provided for me. I have chosen not to add such basic, common code. If it is needed, I can add it. I will add what the Edit Action looks like:
public ActionResult Edit(string id)
{
Report report = db.Reports.Find(id);
return View(report);
}
It accepts a string as an id, ReportId is the id used and it IS a string. It is a randomly generated GUID string made with the GUID.NewGuid().ToString() function. I will also be doing the comparison of names with:
Model.UserName == User.Identity.Name.ToString()
Which was shown earlier. Sorry if this is too much text, I wanted to provide as much info as possible and not make anyone mad. If more info is needed, it can certainly be provided. So at the end of the post, the major question actually comes down to: which of the above two methods is best? And, if it's the first one, how do I implement something like that?
Thanks for your help!
Unless I'm completely misunderstanding you, you just want .Where()
Like this:
var reports = db.Reports.Where(r => r.genre == inputGenre);
This would get you an IEnumerable of Report, which you could then use however you wish.

Categories