Data is not inserting to the database - asp.net-mvc-4

I am new to asp .net MVC 4.
I have one text box and the text box value I am fetching from one table.But while clicking on submit button this value I want to insert into different table , which is not inserting and showing error.It is taking value as null.
coding
View
#Html.TextBox("empname", (string)ViewBag.empname, new { #readonly = "readonly" })
controller
[HttpGet]
public ActionResult Facilities()
{
mstEmpDetail emp = new mstEmpDetail();
emp = db.mstEmpDetails.Single(x => x.intEmpId == 10001);
ViewBag.empname = emp.txtEmpFirstName;
return View();
}
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc)
{
var empname1 = ViewBag.empname;
bc.txtfirstName = empname1;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
While I was working with normal text box it was inserting properly,but when I have retrieve
fro DB then i am getting this problem ?
How to solve this problem ?

Viewbag is a one way street - you can use it to pass information to the view, but you cannot use it to get the information from the view. The statement ViewBag.empname in your POST method has a value of null in your code.

As suggested by #dotnetom, ViewBag is a one way street. MVC is stateless so a POST request is not a "Round Trip" from previous get request. Thus your ViewBag can not hold its state.
MVC can determine (and construct) your action parameters from Form Parameters. In your case you have added a textbox with name "empname". So you should get this value as parameter in your POST request.
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc, string empname)
{
bc.txtfirstName = empname;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
This would be simplest of solution given your problem. More appropriate would be binding your textbox directly with you model property. This way you will not have to worry about retrieving and assigning property value to model in your controller.

I think the problem is when you are using var empname1 = ViewBag.empname; in post controller because ViewBag.empname lost its value at that time.

Related

sitefinity ActionResult missing query string

I have widget and in the ActionResult method it get the query string as parameters. The widget takes the query string and calls a API. Is there anyway I can display a message to the view if its missing the query string?
Code
public ActionResult Index(string UserId, string BlogId)
Yep, do whatever you want
if(String.IsNullOrEmpty(UserId)){
// you get the idea
}
I would do one of the following
Add a property to the model, then handle that state in the view
Load a custom view that's just the message (cleanest)
Check for the empty querystring and do a return this.RedirectPermanent(url); to add the querystring to the page so there's no way it loads without something.

Why is my record being deleted from the db when I attempt to update the record from entity framework MVC?

When I attempt to update a record from entity framework the record is being deleted from the table. There are no errors thrown so it really has me baffled what is happening.
I am fairly new to entity framework and asp.net. I've been learning it for about a month now.
I can update the record without any issues from SQL Server but not from vs. Here is the code to update the db:
// GET: /Scorecard/Edit/5
public ActionResult Edit(int id, string EmployeeName)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CRS_Monthly crs_monthly = GetAgentById(id);
crs_monthly.EmployeeName = EmployeeName;
if (crs_monthly == null)
{
return HttpNotFound();
}
return View(crs_monthly);
}
// POST: /Scorecard/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="REC_ID,Cur_Plan,Plan_Update,Comments,Areas_Improve,Strengths,UPDATED_BY,UPDATED_TIME,Agent_Recognition")] CRS_Monthly crs_monthly)
{
if (ModelState.IsValid)
{
crs_monthly.UPDATED_TIME = DateTime.Now;
crs_monthly.UPDATED_BY = Request.LogonUserIdentity.Name.Split('\\')[1];
db.Entry(crs_monthly).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(crs_monthly);
}
When I run the debugger crs_monthly is valid and looks fine until db.SaveChanges(). Any help is greatly appreciated!
You should never save an instance of your entity created from a post, especially when you're utilizing Bind to restrict which properties are bound from the post data. Instead, always pull the entity fresh from the database and map the posted values on to it. This ensures that no data is lost.
Using Bind is a horrible practice, anyways. The chief problem with it is that all your properties are listed as string values, and you're introducing maintenance concerns. If remove one of these properties or change the name, the Bind list is not automatically updated. You must remember to change every single instance. Worse, if you add properties, you have to remember to go back and include them in this list or else your data just gets silently dropped with no notice.
If you need to only work with a subset of properties on your entity, create a view model containing just those properties. Then, again, map the posted values from your view model onto an instance of your entity pulled fresh from the database.

Redirect to action passes null instead of object

My MVC4 project uses the RedirectToAction() to pass values to another controller.
The problem is, it passes null instead of a value
[HttpGet]
public ActionResult MyProduct(product prod)
{
return RedirectToAction("Index", "MyController", new { prod = prod});
}
This accurately redirects to my MyController which is
public ActionResult Index(Product prod)
{
// prod is null :(
}
I put on a watch in the MyProduct controller, the prod object has a value. The properties do not have values :( it is null
Why does it become null when I pass the object between controllers?
You mistyped you parameter name that you are expecting at your action change it to prod because the prod is a part of RouteValueDictionary which will be collected by the same parameter as defined askey in the dictionary
return RedirectToAction("Index", "MyController", new { prod = prod});
Update
You cannot pass a model object via route parameters via RedirectToAction if I understood your question correctly, instead you can pass specific properties required to be send or you can use the TempData
You can't send data with a RedirectAction. That's because you're doing a 301 redirection and that goes back to the client.
When you redirect you mainly have the query string as a means to pass data to the other request. The other approach is to use TempData which stores data away on the server and you can retrieve it on the next request. By default TempData uses Session.
Consider this image for getting the ways of passing data between Model-View-Controller
Your function parameter name doesn't match in your RedirectToAction().
You should change it like this:
return RedirectToAction("Index", "MyController", new { prod = prod});

how do i create a dynamic view for data entry

What i want in the view is to spit out the fields that are part of the Department and Employee models depending on whichever one gets mentioned in the URL.
say for example department model has 5 fields
How do i create a view (dynamic/not strongly typed) that automatically displays the fields based on the model and let the user enter the values?
[HttpGet]
public ActionResult Create(string process)
{
if (process.Equals("Department"))
{
var model = new Department();
return View(model);
}
else if (process.Equals("Employee"))
{
var model = new Employee();
return View(model);
}
else
return View();
}
You can pass it as an object. You could also pass it in the viewdata (or viewbag). For both of these ways you would also need to include a flag so you know which one you should cast to. Both of these ways in my opinion though are hokey and prone to problems.
Another way would be to create a view model that combines both models. I personally would try to keep them separate and use separate calls \ views for each, depending on the requirements.

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[X]', but this dictionary requires a model item of type 'X'

*CORRECTION
The problem occurs when my view is called to populate a list from my user table.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mike.Models.User]', but this dictionary requires a model item of type 'Mike.Models.User'.
Here is my controller action:
public ActionResult Registration(Mike.Models.User user)
{
if (ModelState.IsValid)
{
using (var db = new UserContext())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(user.password);
var sysUser = db.Users.Create();
sysUser.LastName = user.LastName;
sysUser.FirstName = user.FirstName;
sysUser.Email = user.Email;
sysUser.password = encrypPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.UserID = user.UserID;
db.Users.Add(sysUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
return View(user);
}
Can someone please help me.... There are responses to similar questions on the internet but I believe mine is unique.. I have searched for weeks to no avail.
Thanks in advance,
Renior
Here is my simple controller action...
public ActionResult Index()
{
return View(db.Users.ToList());
}
and my razor syntax.
#model IEnumerable
Im trying to populate a view of my user table list..
In your Registration view at the top where your model declaration is, instead of this:
#model List<Mike.Models.User>
you need to have:
#model Mike.Models.User
You probably used strongly typed scaffolding feature to generate your view but instead of details option you chose a list option...
Take this at face value - yours is not unique. Your problem is you are passing an array of user to a controller action that expects a user.
You need to post your HTML but it is probably something like #model List user or something instead of a single user.
If your model represents a single user then pass that to the controller. If opposite, do opposite,
If you want to pass a list to the controller use list users
edit
make your razor syntax
#model Mike.Models.User