ASP.NET MVC store Hebrew to SQL Server - c#

I have a form which pass a single data in hebrew, from the user (UI) to the SQL Server database.
For some reason the data stored in SQL Server like "???????".
If I go to the database and edit the value "???????" to the actual word in Hebrew, it saves it in Hebrew.
The field in the database is nvarchar
Why when the value pass trough the code to the database it stored like "??????" ?
cshtml:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Album</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AlbumName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AlbumName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AlbumName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="צור אלבום" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
public ActionResult Create()
{
return View();
}
// POST: Albums/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AlbumId,AlbumName")] Album album)
{
if (ModelState.IsValid)
{
db.Albums.Add(album);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(album);
}

In your SLQ Server database change the DataType of your column AlbumName:
var char(xxx) => nvarchar(xxx)
In Code First Apporach you should have Unicode set to True

Related

c# MVC code for the Editing Button, but clicking on the Edit button does not post it

I use the following code for the Editing Button, but clicking on the Edit button does not post it
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PageID,GroupID,Title,ShortDescription,Text,Autor,Tags,Visit,ImageName,ShowInSlider,CreatDateTime")] Page page,HttpPostedFileBase imgUp)
{
if (ModelState.IsValid)
{
if (imgUp != null)
{
if (page.ImageName != null)
{
System.IO.File.Delete(Server.MapPath("/PageImages/" + page.ImageName));
}
page.ImageName = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
imgUp.SaveAs(Server.MapPath("/PageImages/" + page.ImageName));
}
pageRepository.UpdatePage(page);
pageRepository.save();
return RedirectToAction("Index");
}
....
I have separate data layer and repository and I use the following code for the Editing Pages Controller, but with clicking on the Edit button does not post form. Though it works well for creation and delete btn. my view code is:
<div class="form-horizontal">
<h4>Page</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PageID)
#Html.HiddenFor(model => model.Visit)
#Html.HiddenFor(model => model.CreatDateTime)
#Html.HiddenFor(model => model.ImageName)
<div class="form-group">
#Html.LabelFor(model => model.GroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GroupID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GroupID, "", new { #class = "text-danger" })
</div>
</div>
....
<div class="form-group">
#Html.LabelFor(model => model.ImageName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="imgUp" id="imgUp"/>
#Html.ValidationMessageFor(model => model.ImageName, "", new { #class = "text-danger" })
#if (Model.ImageName != null)
{
<img src="/PageImages/#Model.ImageName" class="thumbnail" style="max-width:150px" />
}
.....
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
i trace my code and find this eror:
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2018-04-25T08:10:44.3663705Z","tags":{"ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"Laptop-erfan","ai.operation.name":"GET PageGroup
above horizontal form tag is this code:
#model DataLayer.Page
#{
ViewBag.Title = "Edit";}<h2>Edit</h2>#using (Html.BeginForm("Edit", "Pages", FormMethod.Post, new { enctype = "multipart/form-data" })){ #Html.AntiForgeryToken()
As mentioned in the comments it doesn't look like you have a form in your view. You can add one using:
#using (Html.BeginForm()) {
<!-- form contentshere -->
}
BeingForm has several overloads as well that you can use to change where it goes to, form method (GET/PUT) and set html attributes.
You need to add the complete form page into a Form tag.
please Use
#using (Html.BeginForm()) {
//Put your complete code inside this form...
}
It will create the Form tag with specified actions and type.
You can also specific the custom action method and type of the method as well.

System.InvalidOperationException: When submitting a message

I am receiving the error message above. I have looked at other's issues and can't seem to pinpoint the error. Here is the code that I have for the controller. Here is the error that I am getting :
System.InvalidOperationException: The ViewData item that has the key 'RecieverID' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'
public ActionResult Create()
{
ViewBag.RecieverID = new SelectList(db.AspNetUsers, "Id", "Email");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecieverID,TEXT")] Message message)
{
if (ModelState.IsValid)
{
var mes = new Message
{
SenderID = User.Identity.GetUserId(),
DATETIMEMADE = DateTime.Now,
TEXT = message.TEXT
};
db.Messages.Add(mes);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ReceiverID = new SelectList(db.AspNetUsers, "Id", "Email", message.RecieverID);
return View(message);
}
After that here is my view for creating a message:
#model MUE.Models.Message
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Message</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RecieverID, "RecieverID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RecieverID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RecieverID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TEXT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TEXT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TEXT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Not sure where the issue is coming from but any help would be greatly appreciated.
First off, and not to be a grammar Nazi, but it should be "Receiver" not "Reciever".
Second, model.RecieverID indicates a single field, not a collection.
"new SelectList(..." is collection.
Please refer to this:
MVC - Set selected value of SelectList
You could create a ViewModel for the page such as:
public class MyViewModel
{
public SelectList ReceiverList
public MUE.Models.Message ReceivedMessage
}
Assign your values in the controller and then do something like:
#Html.DropDownListFor(model => model.ReceivedMessage.ReceiverID, Model.ReceiverList, new { #class = "form-control" })

How to pass a static value of field(View1) to another field in (View2) in ASP.Net [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi can you help in sending a static value of the field in another view field..
so when the user clicked the button it will directly go to the page
my view page of the static value
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Customer</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #Value = "5", #readonly = "readonly", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Pay" class="btn btn-default" />
</div>
</div>
</div>
}
to this view
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="form-group">
#Html.LabelFor(model => model.Payment.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Payment.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Payment.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
Controller 1
public ActionResult Pay(Payment apsp)
{
decimal amount = apsp.Amount;
Payment pay = new Payment
{
Amount = amount
};
return RedirectToAction("Create");
}
Model
public decimal Amount{ get; set; }
Currently your Pay action method returns a RedirectResult, which is basically a 302 response which tells the browser to make a new HTTP GET call to the Create action method url. If you want to pass some data, you should return the view instead of this redirect result and pass the view model to the View method call.
So replace
return RedirectToAction("Create");
with
return View("Create",pay);
Also there is no reason to create a new object if you are only reading one property and assigning it to same object type.
public ActionResult Pay(Payment apsp)
{
return View("Create",apsp);
}
But from your question, It looks like your first view and second view are strongly typed to different view models. For the above code to work, Both should be strongly typed to same view model (as you are passing the same object of Payment)
Note. It is possible to pass (minimal) data via ReidrectToAction method call. Read the below post for more information about different ways to achieve that.
How do I include a model with a RedirectToAction?
I will assume that you know how the HttpPost and HttpGet work.
You can pass your viewmodel via TempData like this:
[HttpGet]
public ActionResult Pay()
{
return View(new Payment());
}
[HttpPost]
public ActionResult Pay(Payment payment)
{
TempData["Payment"] = payment;
return RedirectToAction("Create");
}
[HttpGet]
public ActionResult Create()
{
if (TempData["Payment"] == null) throw new Exception("Error");
var payment = TempData["Payment"] as Payment;
return View(payment);
}

How to auto fill fields in a form using #Html.EditorFor in ASP.net MVC 5?

I'm using an autogenerated form from visual studio for asp.net mvc 5 that saves information to a database. It's the create view with the standard scaffolding etc from asp.net with entity framework.
I like the way the form looks, but I need one field (datecreated) to at least be auto filled, (but preferably autofilled and hidden). The problem is I don't understand the autogenerated code at all and my efforts to look it up have not been successful. Nor have my efforts to understand it. I'm still a beginner with html helpers, which I think these are.
Here is the form element I am working with. The part in the middle is the part I need to change to autofill (the date created field), I think the relevant part is changing the EditorFor. but I don't know:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>New Patient:</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
... //other form items removed for simplicity
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateCreated, "", new { #class = "text-danger" })
</div>
</div>
... //more items left out for simplicity
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
And the auto generated controller for this part looks like this:
// GET: Subjects/Create
public ActionResult Create()
{
return View();
}
// POST: Subjects/Create
// 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 Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,DateCreated,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
{
if (ModelState.IsValid)
{
db.SubjectDatabase.Add(subject);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subject);
}
If you dont know how I can autofill and or hide the form element datecreated, could you please point me to where I might learn to figure this out myself. I think I am reasonable at programming, I just don't understand html helpers well, or the bind function in the controller.
Remove this part from your View
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateCreated, "", new { #class = "text-danger" })
</div>
</div>
And then, inside your Controller remove DateCreated from Bind attribute and assign DateCreated property:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
{
if (ModelState.IsValid)
{
subject.DateCreated = DateTime.Now; //if you want UTC time, use DateTime.UtcNow
db.SubjectDatabase.Add(subject);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subject);
}
The #Value can also be used to prefill in spots by using #Html.EditorFor:
Example:
#Html.EditorFor(c => c.Propertyname, new { #Value = "5" })
There is more information to be found at:
Html.EditorFor Set Default Value

Model not populating on POST

I created a simple class to test this directly, on the Edit POST action I was under the impression if a property is not in the form it will use the value which exists in the database already, instead it is getting set to null and overwriting any values.
This is from the scaffold generation, lets say I comment out Password and Password Confirmation because I don't want them to edit it, so they will get left out of the POST values.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PasswordConfirmation, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PasswordConfirmation)
#Html.ValidationMessageFor(model => model.PasswordConfirmation)
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
So the request would look like this:
__RequestVerificationToken=wcxt2SbPmLuI-FzGh7b0okDgfFIXacVKnvvuYpVkgJjpNEAgCbMzHTeMQv61xhbxch0kId6nh6mK-qoKML3CHpLOfk1SawIQIpdtVicWkys1&ID=1&Email=foo.bar%40test.com&FirstName=foo&LastName=bar
And here I simply want to save the values that were edited and any values which were not included use the original values instead.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Email,FirstName,LastName,Password,PasswordConfirmation")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
This is just an example to help me understand how to object gets populated when it's not in the form, if anyone could elaborate or point to resources which clearly show how the model is populated when the values aren't explicitly in the POST request that would be awesome.
I was under the impression if a property is not in the form it will
use the value which exists in the database already
That is not true. How does the form (just some HTML in the client browser) knows what value you have in the database ?
You have 2 solutions
1) In your HttpGet method, Send all the properties of your entity to the form, but don't display those to user. Keep in hidden fields inside the form and when you post the form, It will be available.
public ActionResult Edit(int id)
{
var vm = new EditUserVM();
var user = GetUserFromYourDb(id);
vm.Name = user.Name
vm.Email= user.Email
//The below property you don't want user to edit in form. But still sending.
vm.Token= user.Token
return View(vm);
}
in your view
#model EditUserVM
#using(Html.Beginform())
{
#Html.TextBoxfor(s=>s.Name)
#Html.TextBoxfor(s=>s.Email)
<!-- Hidden field here -->
#Html.HiddenFor(s=>s.Token)
#Html.HiddenFor(s=>s.UserId)
<input type="submit" />
}
2) If you do not wish to send all the fields to form, You may try this.(I recommend this). Have only fields which you want the user to edit in your GET form and In the HttpPost action method, Read the existing entity again from the database and update the fields with the values you received from the form. Your other field values stays same.
public ActionResult Edit(int id)
{
var vm = new EditUserVM();
var user = GetUserFromYourDb(id);
vm.Name = user.Name
vm.Email= user.Email
return View(vm);
}
in your view
#model EditUserVM
#using(Html.Beginform())
{
#Html.TextBoxfor(s=>s.Name)
#Html.TextBoxfor(s=>s.Email)
#Html.HiddenFor(s=>s.UserId)
<input type="submit" />
}
And in your HttpPost
[HttpPost]
public ActionResult Edit(EditUserVM model)
{
var existingUser = GetUserFromYourDb(model.UserId);
existingUser.Name = model.Name;
existingUser.Email = model.Email;
SaveUser(existingUser);
return RedirectToAction("UserSaved");
}

Categories

Resources