Displaying Data from the database taking Order Id as input in mvc4 - asp.net-mvc

I am new to asp and I would like to ask you for some help. I built store with MvcMusicStore tutorial help.Now I want to search in the database by using OrderId.As soon as the orderid is and if we click on the submit button it should display the corresponding rows from the database. My method is as follows
public ActionResult SearchOrder(int? myid)
{
var s = from sp in db.Railways
select sp;
string oid = myid.ToString();
if (!string.IsNullOrEmpty(oid))
{
s = s.Where(st => st.OrderID == (Convert.ToInt16(oid)));
}
return View(s.ToList());
}
Also i tired with the code as
public ActionResult SearchOrder(int? myid)
{
if (id != null)
{
if (ViewBag.OrderID == id.Value)
{
s = s.Where(st => st.OrderID == id);
}
}
return View(s);
}
In the second method when i tried it is neither displaying the contents nor showing the error.
Pls do help me.

Try this:
public ActionResult SearchOrder(int? myid)
{
var s = from sp in db.Railways
select sp;
if (myid.HasValue)
{
s = s.Where(st => st.OrderID == myid.Value);
}
return View(s.ToArray());
}
First your example will not work because string oid = myid.ToString(); will not be null or empty string if myid is null; Second example will fail (ViewBag.OrderID == id.Value) condition and moreover will not compile.

Related

How to update existing rows using Entity Framework?

I have the following one to many table as below. I am experiencing issue when it comes to editing the existing rows with the following code. Please understand that I am pretty new to the ET relationship, so any detailed explanation would be greatly appreciated. Why it is returning null values?
public void UpdateReportGroup(TReportHeaderModel model)
{
if (model.THeaderTitle == null)
{
throw new Exception("Report Group Title must be filled in");
}
if (model.THeaderTitle.Length <= 0)
{
throw new Exception("A Report Group Title must be filled in.");
}
using (var connection = new TReportEntitiesConnection())
{
var header = connection.THeaders.SingleOrDefault(f => f.ID == model.ID);
var reports = connection.TReport.Where(f => f.THeaderID == model.ID);
connection.TReport.RemoveRange(reports);
foreach (var urls in model.TReports)
{
connection.TReport.Add(new TReport()
{
TReportName = urls.name,
URL = urls.url,
});
}
connection.THeaders.Add(header);
connection.SaveChanges()
}
}
Everytime, I debug it,it is giving null values for the 'TReport' table.
My create new rows works perfectly with the following code. Meaning, I am returning the correct form with correct field names.
public void CreateReport(TReportHeaderModel model)
{
if (model.THeaderTitle == null)
{
throw new Exception("Report Group Title must be filled in");
}
if (model.THeaderTitle.Length <= 0)
{
throw new Exception("A Report Group Title must be filled in.");
}
using (var connection = new TReportEntitiesConnection())
{
var header = new THeader()
{
ClientID = model.ClientID,
THeaderTitle = model.THeaderTitle,
RowNumber = model.RowNumber
};
foreach (var urls in model.TReports)
{
header.TReports.Add(new TReport()
{
TReportName = urls.name,
URL = urls.url
});
}
connection.THeaders.Add(header);
connection.SaveChanges();
}
}
As you can see, I am following DI pattern, and therefore I am calling these two methods in my controller as below:
[HttpPost]
public ActionResultModel CreateReportAPI([FromBody] TReportHeaderModel model) //attempt 3
{
try {
if (ModelState.IsValid)
{
var isValid = _tReportingService.HeadernameExists(model.THeaderTitle);
if (!isValid)
{
Console.WriteLine("it does not exist");
var user = this.GetCurrentUserAccount();
model.ClientID = user.SelectedClient.ID;
_tReportingService.CreateReport(model);
}
else //Update method comes till here and it goes //straight to the error
{
Console.WriteLine("it exists");
var user = this.GetCurrentUserAccount();
model.ClientID = user.SelectedClient.ID;
_tReportingService.UpdateReportGroup(model);
}
}
return new ActionResultModel()
{
Success=true,
Message="Report Group Successfully Saved."
};
}
I guess it would be the last time I'd posting questions here as I understood that it takes you nowhere if you just ask so I'd rather research more and keep trying it until I got it so here I am answering my own question as I'd solved it.
As the model gets generated from WebApi which is completely detached from ET, I am loading the database first and compare which children have been added, deleted & updated. Here is an example of perfect one to many relationship's update/delete.
using (var connection = new TReportEntitiesConnection())
{
var header = connection.THeaders.Include("TReports").SingleOrDefault(f => f.ID == model.ID);
if (header != null)
{
header.THeaderTitle = model.THeaderTitle; //update parent
}
foreach (var existingChild in header.TReports.ToList())
{
if (!model.TReports.Any(c => c.ID == existingChild.ID))
connection.TReport.Remove(existingChild);
}
foreach (var url in model.TReports)
{
var existingChild = header.TReports
.Where(c => c.ID == url.ID)
.SingleOrDefault();
if (existingChild != null)
{ //update child
connection.Entry(existingChild).CurrentValues.SetValues(url);
}
else
{
var newChild = new TReport
{
TReportName = url.name,
URL = url.url,
};
header.TReports.Add(newChild);
}
}
connection.SaveChanges();
}

Edit & Delete object with ViewModel

I've successfully implemented a viewmodel so I can create and return items from my database using two tables. My issue is editing and deleting individual items.
I was able to edit/delete when I was using just one table, but with two, i've run into a snag.
My view uses a viewmodel now. I am not able to figure out how to pass the specific object id when Passing an id and TransactionViewModel Viewmodel into my Edit method Parameters.
Here is my old Edit and Edit post.
public ActionResult Edit(int id = 0)
{
Transactions transactions = _db.Transactions.Find(id);
if (transactions == null)
{
return HttpNotFound();
}
return View(transactions);
}
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Edit(TransactionViewModel viewModel)
{
var transactionType = viewModel.Transaction.TransactionType;
if (ModelState.IsValid)
{
//If the transaction category is an Expense, set it to a negative so we can calculate later.
if (transactionType == Classes.Constants.Expense || (transactionType == Classes.Constants.Payment && viewModel.Transaction.Amount < 0))
{
viewModel.Transaction.Amount *= -1;
}
var transaction = new Transactions()
{
ClientId = viewModel.Transaction.ClientId,
Amount = viewModel.Transaction.Amount,
Date = viewModel.Transaction.Date,
Category = viewModel.Transaction.Category,
Description = viewModel.Transaction.Description,
TransactionType = viewModel.Transaction.TransactionType
};
_db.Entry(transaction).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
I've tried this for my get Edit, but it returns the same thing each time and not the one specified on my view. Ex. If click edit for Client D, it will pull up the edit screen for Client A and I cannot save it. I have an edit and delete button in my viewable table next to each transaction using an #Html.ActionLink().
public ActionResult Edit(TransactionViewModel viewModel)
{
if (ModelState.IsValid)
{
var transactions = from t in _db.Transactions
join c in _db.Clients
on t.ClientId equals c.ClientId
select new TransactionViewModel() { Clients = c, Transaction = t };
return View(transactions.FirstOrDefault());
}
return RedirectToAction("Index");
}
Any help would be appreciated. Thanks!
I bet that view is being cached. There are many different ways to influence caching in the controller. If you want to simply remove cacheing, in your case for editing, then decorate that action with the following:
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult Edit(TransactionViewModel viewModel)
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult Edit(int id = 0)
Note: You will have to clear cache to get the new view with the no cache set above.
Your Get Edit method should still accept an int ID to select the correct record form the database and it should return the view model.
something like this:
public ActionResult Edit(int id = 0)
{
var transactions = from t in _db.Transactions
join c in _db.Clients
on t.ClientId equals c.ClientId
where t.id == id
select new TransactionViewModel() { Clients = c, Transaction = t };
return View(transactions.FirstOrDefault());
}

Why does one Web API method work, whereas the other does not?

One of my Web API methods works perfectly, and the other not at all.
By works perfectly, I mean this:
The other one, though, doesn't seem to even know about itself. It answers the browser request with:
The code seems to be set up the same for both of them, so I don't know why one works like a charm and the other fails so thuddily.
The pertinent code is:
CONTROLLER
public class DepartmentsController : ApiController
{
private readonly IDepartmentRepository _deptsRepository;
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository is null");
}
_deptsRepository = deptsRepository;
}
[Route("api/Departments/Count")]
public int GetCountOfDepartmentRecords()
{
return _deptsRepository.Get();
}
[Route("api/Departments")]
public IEnumerable<Department> GetBatchOfDepartmentsByStartingID(int ID, int CountToFetch)
{
return _deptsRepository.Get(ID, CountToFetch);
}
REPOSITORY
public class DepartmentRepository : IDepartmentRepository
{
private readonly List<Department> departments = new List<Department>();
public DepartmentRepository()
{
using (var conn = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Freebo;Password=RunningOnEmpty;Data Source=C:\CDBWin\DATA\CCRDAT42.MDB;Jet OLEDB:System database=C:\CDBWin\Data\nrbq.mdw"))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT td_department_accounts.dept_no, IIF(ISNULL(t_accounts.name),'No Name provided',t_accounts.name) AS name FROM t_accounts INNER JOIN td_department_accounts ON t_accounts.account_no = td_department_accounts.account_no ORDER BY td_department_accounts.dept_no";
cmd.CommandType = CommandType.Text;
conn.Open();
int i = 1;
using (OleDbDataReader oleDbD8aReader = cmd.ExecuteReader())
{
while (oleDbD8aReader != null && oleDbD8aReader.Read())
{
int deptNum = oleDbD8aReader.GetInt16(0);
string deptName = oleDbD8aReader.GetString(1);
Add(new Department { Id = i, AccountId = deptNum, Name = deptName });
i++;
}
}
}
}
}
public int Get()
{
return departments.Count;
}
private Department Get(int ID) // called by Delete()
{
return departments.First(d => d.Id == ID);
}
If entering:
http://shannon2:28642/api/Departments/Count
in the browser works to execute the Controller's GetCountOfDepartmentRecords() method, why does entering:
http://localhost:28642/api/Departments/5/6
(or:
http://localhost:28642/api/Departments/1/5
etc) not work to execute the Controller's GetBatchOfDepartmentsByStartingID() method?
Your route is missing its parameters.
[Route("api/Departments/{ID:int}/{CountToFetch:int}")]
This question looks similar to your other question below:
Why is my Web API call returning "No action was found on the controller 'DPlatypus' that matches the request"?
If you are expecting the values to come from a non-query string part of a url, you need to define them in the route template. So, it should be
[Route("api/Departments/{id}/{countToFetch}")]
Following is a good article to read about routing and action selection in Web API:
http://www.asp.net/web-api/overview/web-api-routing-and-actions

At edit in webgrid in mvc3 why ModelState.IsValid is false as condition is true?

[HttpPost]
public ActionResult Index(SecurityMappingModel objModel)
{
//edit code
if (objModel.Id != Guid.Empty)
{
if (ModelState.IsValid)
{
mappings = (List<SecurityMappingModel>)Session["Mappings"];
var objRemove = mappings.FirstOrDefault(m => m.Id == objModel.Id);
if (objRemove != null)
{
mappings.Remove(objRemove);
mappings.Add(objModel);
ViewBag.Mappings = mappings;
}
Session["Mappings"] = mappings;
return RedirectToAction("Index");
}
inside objModel one of the field is having value 0 as it is a textfield i'm putting value into it but inside Controller oject objModel showing that field value is zero :( :( why???
Apparently one of your model values is not valid. You should be able to find out which one by looking at the items in ModelState.Values. Each item has an Errors property.
The result of this line should contain at least one item:
var errors = ModelState.Values.Where(value=>value.Errors.Any());

Break new Line problem - C# .NET MVC

It's good day today! But... :)
I have the following problem: I have a controller that updates a type_text field in a Mysql DB. The user types text in texarea, clicks "Update" and, oh magic, the text is posted to the database. But without a break...
In the controller i have:
[Authorize]
[HttpPost]
public string EditComment(FormCollection formValues)
{
var Commenter = User.Identity.Name;
Int64 id = Convert.ToInt64(Request.Form["id"]);
string formValue = Request.Form["value"];
formValue = formValue.Replace("\r\n", "<br/>").Replace("\r", "<br/>");
comments updateCommnets = db.comments.SingleOrDefault(d => d.id == id && d.commenterName == Commenter);
updateCommnets.comment = formValue;
db.SaveChanges();
return formValue;
}
It's making me crazy for 2 days...
Can Somebody help me? Thanks a lot!
UPDATED
I use jeditable to perform inline editing. Example of post string: value=Some+text%0ASome2+text2
I would store the text as is in the database without converting \r\n to <br/>:
[Authorize]
[HttpPost]
public ActionResult EditComment(string value, long id)
{
var commenter = User.Identity.Name;
var updateCommnets = db.comments.SingleOrDefault(d => d.id == id && d.commenterName == commenter);
updateCommnets.comment = value;
db.SaveChanges();
return Content(value, "text/plain");
}
Then I would write a custom HTML helper to format the values in the view if necessary to show those comments.
public static MvcHtmlString FormatComment(this HtmlHelper html, string comment)
{
if (string.IsNullOrEmpty(comment))
{
return MvcHtmlString.Empty;
}
var lines = comment
.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None
)
.Select(x => HttpUtility.HtmlEncode(x))
.ToArray();
return MvcHtmlString.Create(string.Join("<br/>", lines));
}
and then in the view:
#Html.FormatComment(Model.Comment)
Do not convert the text that is sent to the database.
Use:
#MvcHtmlString.Create(value)
Here's the manual

Resources