How to replace string with character ASP.NET - c#

is there a way where I can replace multiple strings e.g.. hot , cold , good, with ###?
The text field
div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
Controller
public ActionResult Create()
{
return View(new Charity());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,DisplayName,Date,Amount,Comment")] Charity charity)
{
if (ModelState.IsValid)
{
db.Donations.Add(charity);
db.SaveChanges();
return RedirectToAction("Additionalinfo", "Charities");
}
return View(charity);
}
Model
public class Charity
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string DisplayName { get; set; }
[DataType(DataType.Currency)]
[Range(2, Int32.MaxValue, ErrorMessage = "Atleast £2.00 or a whole number please")]
public int Amount { get; set; }
public Double TaxBonus { get; set; }
public String Comment { get; set; }
}
Can I replace multiple texts with one code function or does it have to be individually for each string?? I am new to MVC and ASP.NET so pretty confusing.

So you can do that in your controller.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,DisplayName,Date,Amount,Comment")] Charity charity)
{
if (ModelState.IsValid)
{
if(!string.IsNullOrEmpty(charity.Comment)
{
var comment = charity.Comment.ToLower().Replace("hot","###").Replace("cold","###");
charity.Comment = comment;
}
db.Donations.Add(charity);
db.SaveChanges();
return RedirectToAction("Additionalinfo", "Charities");
}
return View(charity);
}

Related

One of two model for View is always null in MVC 5

In my MVC5 application I have two model Order and File as following:
public class Order
{
public int OrderID { get; set; }
public string OrderName{ get; set; }
}
public class File
{
public HttpPostedFileBase[] files { get; set; }
}
I want edit objects of both classes in single view, so I create parent class:
public class MainContext
{
public Order Order { get; set; }
public File File { get; set; }
}
In the view I have this:
#using (Html.BeginForm("Create", "Order", FormMethod.Post, new { encType = "multipart/form-data" }))
#Html.AntiForgeryToken()
<div class="form-group">
<label>OrderName</label>
#Html.EditorFor(model => model.Order.OrderName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Order.OrderName, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.File.files, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.File.files, "", new { #type = "file", #multiple = "multiple", })
#Html.ValidationMessageFor(model => model.File.files, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success btn-lg btn-block" />
</div>
The Controller
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OrderName")] Order order, HttpPostedFileBase[] files)
{
if (ModelState.IsValid)
{
db.Order.Add(order);
db.SaveChanges();
if (files != null)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
file.SaveAs(ServerSavePath);
}
}
}
return RedirectToAction("Index");
}
}
Now the problem .. after I submit the form I got order values in Create action BUT files is always NULL !
What I miss
Thanks in advance
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MainContext model)
{
// here fetch values from model.Order and model.File
}
Instead of fetching two models separately call "MainContext" class in post action, from that you can get all the view values....

return list of ViewModel from model to controller [duplicate]

Whenever I submit the form the model passed into the controller is NULL. I've spent ages looking at this. I think I am missing something fundamental here.
#model VisitorPortal.Models.ReinviteVisitorModel
#using (Html.BeginForm("CreateMeeting", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h3>Reinvitation Details</h3>
<div>The information entered below will be sent to the visitors email address #Model.Info.Email</div>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.Title, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.Title, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.StartTime, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.StartTime, new { #class = "datetimepicker form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.EndTime, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.EndTime, new { #class = "datetimepicker form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#Html.HiddenFor(m => m.NewMeeting.SubjectId, new { #Value = Model.Info.SubjectId })
<input type="submit" class="btn btn-default" value="Send Invite" />
</div>
</div>
}
The Model is:
public class Meeting
{
[Key]
public int Id { get; set; }
public string SubjectId { get; set; }
[Required]
[Display(Name = "Reason for invitation")]
public string Title { get; set; }
[Required]
[Display(Name = "Start Time")]
[DataType(DataType.Time)]
public DateTime StartTime { get; set; }
[Required]
[Display(Name = "End Time")]
[DataType(DataType.Time)]
public DateTime EndTime { get; set; }
public string HostEmail { get; set; }
public string HostMobile { get; set; }
}
public class MeetingsDBContext: DbContext
{
public DbSet<Meeting> Meetings { get; set; }
}
public class ReinviteVisitorModel
{
public Visitor Info;
public Meeting NewMeeting;
public List<Meeting> Meetings;
}
The Controller action is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(Meeting meeting)
{
return RedirectToAction("ReinviteVisitor2", "Home", new { visitorId = meeting.SubjectId });
}
I have fields in the model such as Id which I am expecting the database to populate which I was going to write in the the action CreateMeeting(). Do all fields in the Model have to be used in the form?
The model in your view is typeof ReinviteVisitorModel which means the signature of the POST method must match since your posting ReinviteVisitorModel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(ReinviteVisitorModel model)
alternatively you can use the Prefix property of BindAttribute to strip the NewMeeting prefix from the names of the form controls your are posting.
public ActionResult CreateMeeting([Bind(Prefix="NewMeeting")]Meeting model)
Side note: Remove new { #Value = Model.Info.SubjectId } from the hidden input and instead set the value of NewMeeting.SubjectId in the GET method before you pass the model to the view.
You need to pass ReinviteVisitorModel model in your Action
Update you action with this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(ReinviteVisitorModel model)
{
return RedirectToAction("ReinviteVisitor2", "Home", new { visitorId = model.NewMeeting.SubjectId });
}

HttpPostedFileBase to varbinary(max)

I have just tried a lot of things that I found but at the end nothing successfull.
First I have the next code that just do the things ok but dont save the image.
What should I do to save an image into a varbinarymax? and how to show them to the view next?
view:
<div class="form-group">
#Html.LabelFor(model => model.Logo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.Logo, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.TextBoxFor(model => model.Logo, new { type = "file" })
#Html.ValidationMessageFor(model => model.Logo, "", new { #class = "text-danger" })
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school)
{
if (ModelState.IsValid)
{
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
Model:
public partial class School
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public School()
{
this.Product = new HashSet<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Mail { get; set; }
public int? Phone { get; set; }
public byte[] Logo { get; set; }
public string Small_Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Product> Product { get; set; }
}
Change View First to This:
#using (Html.BeginForm("Create", "Schole", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.Logo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Logo, new { type = "file" })
<input type="submit" value="submit" />
</div>
</div>
}
Change Action To This:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school, HttpPostedFileBase Logo)
{
if (ModelState.IsValid)
{
using (var memoryStream = new MemoryStream())
{
Logo.InputStream.CopyTo(memoryStream);
school.Logo = memoryStream.ToArray();
}
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
}
Now This Logo Save It.
As you don't have posted complete form, here is complete code to upload image and save into DB.
you form must have enctype property.
#using (Html.BeginForm("Index","Home",FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
//your other code
<input type="file" name="logo" />
<input type="submit" value="Save" />
}
And inside your action.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school)
{
if (ModelState.IsValid)
{
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files["logo"].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files["logo"].ContentLength);
}
school.Logo=fileData;
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
It will save file in your Db.

Can not insert my dropdownlist data in database with foreign key in mvc4

I want to pack my data in form with foreign key and send that to database.I collect data from database with controller and show in my view and when I complete the form can not send that to database and see the exception
my controller code is
public ActionResult Register()
{
testContext test = new testContext();
List<SelectListItem> listselecteditem = new List<SelectListItem>();
foreach (Gender item in test.genders)
{
SelectListItem selectlist = new SelectListItem()
{
Text = item.GenderType,
Value = item.GenderID.ToString(),
};
listselecteditem.Add(selectlist);
}
ViewBag.Datalist = new SelectList(listselecteditem, "Value", "Text");
return View();
}
this controller get data from database and send to dropdownlist
and this controller save my data in database
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Person p)
{
using (testContext test=new testContext())
{
if (ModelState.IsValid)
{
try
{
test.persons.Add(p);
test.SaveChanges();
ViewBag.Message="Success";
}
catch (Exception ec)
{
ViewBag.Message = ec.Message;
}
}
}
return View(p);
}
this is my view
#model testmvc.Models.Person
<div class="container">
<div class="row">
<div class="pull-right col-sm-offset-3 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading ">
<p>register</p>
</div>
<div class="panel-body">
#using (Html.BeginForm("Register", "RegisterLogin", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true)
<fieldset>
#Html.AntiForgeryToken()
#if (ViewBag.Messsage != null)
{
<div class="alert alert-success">
<p>#ViewBag.Message</p>
</div>
}
<div class="form-group">
#Html.TextBoxFor(model => model.Fullname, new { #class = "form-control", #placeholder = "Full name" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control input-sm", #id = "last_name", #placeholder = "Username" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.EmailAddress, new { #class = "form-control input-sm", #id = "email", #placeholder = "Email address" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Password, new { #class = "form-control input-sm floatlabel", #id = "first_name", #placeholder = "Password" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Comfirmpassword, new { #class = "form-control input-sm", #id = "last_name", #placeholder = "confirmpassword" })
</div>
<div class="form-group">
#*<select>
#foreach (var item in ViewBag.DataList)
{
<option>#item.Text</option>
}
</select>*#
#Html.DropDownList("Datalist",String.Empty)
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Birthday, new { #class = "form-control input-sm", #id = "password_confirmation", #placeholder = "Birthday yyyy/dd/mm" })
</div>
<div>
<input type="submit" value="Register" class="btn btn-primary">
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
</div>
and my model code
public partial class Person
{
[Key]
public int personID { get; set; }
[Required]
public String Fullname { get; set; }
[Required]
public String Username { get; set; }
[Required]
public String Password { get; set; }
[Required]
[NotMapped]
public String Comfirmpassword { get; set; }
[Required]
public String EmailAddress { get; set; }
[DataType(DataType.DateTime)]
[Required]
public DateTime Birthday { get; set; }
public int GenderID { get; set; }
[ForeignKey("GenderID")]
public virtual Gender Gender { get; set; }
}
[Table("Gender")]
public partial class Gender
{
[Key]
public int GenderID { get; set; }
[Required]
public String GenderType { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
this exception said there is not any viewdata key with "Datalist". how can I solve that and what is my code problem
The reason you are getting this exception is because inside [HttpPost] action you didn't populate the ViewBag.Datalist property, the way you did in your Get action. Since you redisplay the same view and this view requires this information in order to properly render the dropdown, you will need to populate it. To avoid repetition you could place this logic in a separate method:
private SelectList GetGenders()
{
using (testContext test = new testContext())
{
List<SelectListItem> listselecteditem = new List<SelectListItem>();
foreach (Gender item in test.genders)
{
SelectListItem selectlist = new SelectListItem()
{
Text = item.GenderType,
Value = item.GenderID.ToString(),
};
listselecteditem.Add(selectlist);
}
return new SelectList(listselecteditem, "Value", "Text");
}
}
which you are going to call in your 2 actions:
public ActionResult Register()
{
ViewBag.Datalist = GetGenders();
return View();
}
and:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Person p)
{
using (testContext test = new testContext())
{
if (ModelState.IsValid)
{
try
{
test.persons.Add(p);
test.SaveChanges();
ViewBag.Message = "Success";
}
catch (Exception ec)
{
ViewBag.Message = ec.Message;
}
}
}
ViewBag.Datalist = GetGenders();
return View(p);
}

How to save data from Select box in Entity Framework Database relation Many to Many

How to save data from Select box in Entity Framework Database relation Many to Many
There are two classes one weapon and other User..
public class Weapon { } public class User { }
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Wepon
{ public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
}
Which should have relation Many to Many Using FormCollection and Model
User Class
And Weapon Class
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
**public List<Wepon> WeposInList { get; set; }**
}
public class Wepon
{
public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
public List<User> UsersHaveWeponsList { get; set; }// User the List for M to M
}
DBContext
public class DbContexFor : DbContext
{
public DbContexFor()
: base("name=ConnectionStringName")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Wepon> Wepons { get; set; }
}
}
**
The Controller Code
**
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,Type")] User user, FormCollection formData)
{
if (ModelState.IsValid)
{
var ss = formData["ShipFromCountries"].ToString();
user.WeposInList = db.Wepons.Where(c => c.Wepon_Name == ss).ToList();
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
And the Html Code
#model enumVarAction.Models.User
#{
var list = ViewBag.MyList;
ViewBag.Title = "Create";
}
Create Html Page
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeposInList, htmlAttributes: new { #class = "control-label col-md-2" })
<select id="ShipFromCountries" multiple="multiple" name="ShipFromCountries">
<div class="col-md-10">
#foreach (var VARIABLE in list)
{
<option value="#VARIABLE.Wepon_Name">#VARIABLE.Wepon_Name</option>
}
</div>
</select>
</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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
**
Debug at Controller
**
**
Data is Database
**

Categories

Resources