Use json to get data from class members
Before marking it duplicate please understand my problem.
I have a class:
public class SampleModel {
public string fname { get; set; }
}
I want to create a table and fill it with values that my objects hold. I have a json file:
{
"displayname":"First Name",
"codename":"fname"
}
Which contains two things, display name which I want to be the display name of the table heading.
And 2nd is the codename which is the name I have used in my class to name my member.
what I want to do is that the table heading should be taken from json "displayname"
and the values under it should be filled using json's "codename".
Is there is a effective way of doing it?
See also questions close to this topic
-
ASP.NET MVC 4 and DotNetZip , downloads a corrupted Zip file
Hi I am trying to download a zip file that contains some Pdf files using ASP.NET MVC 4 and DotNetZip , I am able to download the zip file but when i open it and tried to extract or even when i try to open a file from that archive it tell me that the zip file is corrupted . here 's the code:
[HttpPost] public JsonResult PrepareMultipleFile(int[] IdArray) { List<Content> contents = new List<Content>(); List<byte[]> byteArrays = new List<byte[]>(); ImageContext _contexte = new ImageContext(); contents = _contexte.contents.ToList(); foreach (var content in contents) { byteArrays.Add(content.image); } Session["FilesData"] = byteArrays; return Json("AllFiles"); } [HttpGet] public FileResult DownloadMultipleFile() { int i = 0; var fname = "allFiles"; List<byte[]> data = (List<byte[]>)Session["FilesData"]; var zipFile = new ZipFile(); using (var outStream = new MemoryStream()) { using (var archive = new ZipFile()) { foreach (var item in data) { using (MemoryStream ms = new MemoryStream(item)) { var entry = archive.AddEntry($"file"+i+".pdf", ms); archive.Save(outStream); i++; } } } outStream.Position = 0; return File(outStream.ToArray(), "application/zip", "all.zip"); }
-
How to DELETE "old File" from a folder? ASP.NET
I'm trying to do an Update method in a GridView where: I want to delete an old image and then replacing it with a new one but, i can't manage to delete the old one when i'm doing the update, it just end in everything replaced in the database & a new image in the folder, but the old image still remains in the folder("images").
BackEnd Code(the update):
protected void gvImages_RowUpdating(object sender, GridViewUpdateEventArgs e) { HttpPostedFile file = ((FileUpload)gvImages.Rows[e.RowIndex].FindControl("FileUpload2")).PostedFile; string fileName = Path.GetFileName(file.FileName); MySqlConnection con = new MySqlConnection(strConnString); string strQuery = "update testingdb.country set Relation=@Relation, Nombre=@Nombre, FileName=@FileName, FilePath=@FilePath where idcountry=@idcountry"; MySqlCommand cmd = new MySqlCommand(strQuery); //string oldFileName = "select FileName from testingdb.country where idcountry=@idcountry"; //string oldFile = Path.GetFileName(Server.MapPath(strConnString + oldFileName)); if (File.Exists(Server.MapPath("images/") + fileName)) { lblFail.Visible = true; lblFail.Text = "Ya existe esta entrada."; TextBox1.Text = ""; } else { File.Delete(Server.MapPath("~/images/") + gvImages.Rows[e.RowIndex].Cells[3].ToString()); //this saves files in the folder "images" file.SaveAs(Server.MapPath("images/" + fileName)); cmd.Connection = con; cmd.Parameters.AddWithValue("@Relation", (gvImages.Rows[e.RowIndex].FindControl("txtRel") as TextBox).Text.Trim()); cmd.Parameters.AddWithValue("@Nombre", (gvImages.Rows[e.RowIndex].FindControl("txtNom") as TextBox).Text.Trim()); cmd.Parameters.AddWithValue("@FileName", fileName); cmd.Parameters.AddWithValue("@FilePath", "images/" + fileName); cmd.Parameters.AddWithValue("@idcountry", Convert.ToInt32(gvImages.DataKeys[e.RowIndex].Value.ToString())); cmd.CommandType = CommandType.Text; try { con.Open(); cmd.ExecuteNonQuery(); gvImages.EditIndex = -1; //File.Delete(oldFile); } catch (Exception ex) { lblFail.Visible = true; lblFail.Text = ex.Message; } finally { con.Close(); con.Dispose(); } this.MostrarImagen(); lblSuccess.Visible = true; lblSuccess.Text = "Exito de Cambios."; } }
i'm using a database to store the path and a folder to store the images.
This is the GridView:
<asp:GridView EmptyDataText="No hay registros en la base de datos!" ID="gvImages" runat="server" DataKeyNames="idcountry" OnRowCommand="gvImages_RowCommand" AutoGenerateColumns="false" OnRowDataBound="gvImages_RowDataBound" Height="300px" OnRowEditing="gvImages_RowEditing" OnRowCancelingEdit="gvImages_RowCancelingEdit" OnRowUpdating="gvImages_RowUpdating"> <Columns> <asp:BoundField DataField="idcountry" HeaderText="ID" ReadOnly="true" /> <%--<asp:BoundField DataField="Relation" HeaderText="Relacion" ReadOnly="true" />--%> <asp:TemplateField HeaderText="Relacion"> <ItemTemplate> <asp:Label ID="lblRelation2" Text='<%# Eval("Relation") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtRel" Text='<%# Eval("Relation") %>'></asp:TextBox> /> </EditItemTemplate> </asp:TemplateField> <%--<asp:BoundField HeaderText="Nombre" DataField="FileName" ReadOnly="true" />--%> <asp:TemplateField HeaderText="Nombre"> <ItemTemplate> <asp:Label ID="lblNombre2" Text='<%# Eval("Nombre") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtNom" Text='<%# Eval("Nombre") %>'></asp:TextBox> /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("FilePath") %>' Height="300" Width="300" /> </ItemTemplate> <EditItemTemplate> <asp:FileUpload ID="FileUpload2" runat="server" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:ImageButton CausesValidation="false" CssClass="btnOPTIONS" runat="server" ImageUrl="~/imgBTN/edit.png" Width="30px" Height="30px" ToolTip="Edit" CommandName="Edit" /> <asp:ImageButton CausesValidation="false" runat="server" ImageUrl="~/imgBTN/delete.png" Width="30px" Height="30px" ToolTip="Delete" CommandName="Delete" /> </ItemTemplate> <EditItemTemplate> <asp:ImageButton CausesValidation="false" CssClass="btnOPTIONS" runat="server" ImageUrl="~/imgBTN/save.png" Width="30px" Height="30px" ToolTip="Update" CommandName="Update" /> <asp:ImageButton CausesValidation="false" runat="server" ImageUrl="~/imgBTN/cancel.png" Width="30px" Height="30px" ToolTip="Cancel" CommandName="Cancel" /> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
-
Java Windows Form Application throws error class not founds
I am trying to do CRUD operation by using net beans . I am using windows authentication for connection sql server with java . When i run the application and clicked the submit button its shows following errors .
Class not found Exception
here is code .
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url="jdbc:sqlserver://KHUNDOKARNIRJOR\\KHUNDOKERNIRJOR;Initial Catalog=3TierInWindowsApplication;Integrated Security=True"; Connection con = DriverManager.getConnection(url); String Query ="Inser into Student (Name,Address,EmailID,Mobile)values (?,?,?,?)"; PreparedStatement pst =con.prepareStatement(Query); pst.setString(1,student_name.getText()); pst.setString(2,address.getText()); pst.setString(3,email_address.getText()); pst.setString(4,mobile_number.getText()); pst.executeUpdate(); JOptionPane.showMessageDialog(null,"Record is inserted "); } catch (Exception ex) { JOptionPane.showMessageDialog(null,"Record is failed to insert "+ex); } }
-
Multiple getJSON requests and element order
The set below runs 4 JSON requests then created a div to get prepended to another div. But I cannot seem to get the order of the items to be consistent. I know it's because there are multiple requests and they load at different times, but I can't figure out how to combine all the requests and pass the variables. If I could get all the requests in the same statement I could just make one large prepend, but I can't seem to get the variables correct.
$(document).ready(function() { if ( $('#main_intranet-main').length ) { $.getJSON("xxx", function(data) { var bibs = data[0].n; var bibs2 = data[1].n; $('div#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Patrons added and expired yesterday</thead><tbody><tr><td><strong>New Patrons</strong></td><td><strong>Expired Patrons</strong></td></tr><tr><td><center>' + bibs + '</center></td><td><center>' + bibs2 + '</center></td></tbody></table></div>'); }); } if ( $('#main_intranet-main').length ) { $.getJSON("xxx", function(data) { var items = data[0].n; $('div#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Items Checked Out Yesterday</thead><tbody><tr><td><center>' + items + ' </center></td></tbody></table></div>'); }); } if ( $('#main_intranet-main').length ) { $.getJSON("xxx", function(data) { var house = data[0].totalcount; $('div#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">In House Use Yesterday</thead><tbody><tr><td><center>' + house + ' </center></td></tbody></table></div>'); }); } if ( $('#main_intranet-main').length ) { $.getJSON("xxx", function(data) { var bibs = data[0].Total; var bibs2 = data[1].Total; var total = bibs - bibs2 $('div#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Net Patrons YTD</thead><tbody><tr><td><center>' + total + '</center></td></tr></tbody></table></div>'); }); } });
-
Deserializing JSON object with dynamic JsonProperty without wrapper class using Jackson
I want to restructure an application so that it uses REST instead of an EJB3Factory which wasn't needed in the first place and only makes trouble with the new server.
Basically I have a class Request:
public class Request { public String name; public String id; public List<? extends someObject> list; // default constructor ... // non-default constructor public Request(String name, String id, List<T> list) { this.name = name; this.id = id; this.list = list; }
The
Request
gets created and using Gson made into a Json object:Gson gson = new Gson(); String payload = gson.toJson(Request);
This then gets sent to the REST API on the server. There Jackson deserializes it. I do not have access to the Jackson implementation there and cannot change it to Gson.
What I am basically trying to do now is to get Jackson to use the non-default constructor to deserialize the object. I know I can annotate the non-default constructor like this:
@JsonCreator public Request(@JsonProperty("name") String name, @JsonProperty("id") String id, @JsonProperty("list") List<T> list) { this.name = name; this.id = id; this.list = list; }
The thing is though that the field name of
list
is set at runtime per reflection and the Gson object that is generated might have it asscenarioName1
for one andscenarioName2
for something else.I have looked at the different solutions provided here on Stack Overflow but none of them could provide me with a solution for my problem. This seemed most helpful but I cannot under any circumstances use a wrapper property nor can I actually map all possibilities.
Anyone got any idea?
EDIT to include examples:
Example 1:
{"name":"someName","id":"first","someScenarioName":[{...}]}
Example 2:
{"name":"someOtherName","id":"second","differentScenarioName":[{...}]}
Since I'm out of town on business that is the best I can do with right now. It's basically the last field having a different name depending on which scenario was chosen beforehand.
-
Adding property to a json object in C#
I'm trying to add a property to a json object, which are not root of the json.
example is below.
{ 'isFile' : 'true', 'Values' : { 'valueName1': 'value1', 'valueName2': 'value2', 'valueName3': 'value3', } }
after the operation, i want the json file to look like below.
{ 'isFile' : 'true', 'Values' : { 'valueName1': 'value1', 'valueName2': 'value2', 'valueName3': 'value3', 'valueName4': 'value4' } }
I have gotten to the point where I can access Values property through below code. Where do I go next?
JObject appSettings = JsonConvert.DeserializeObject<JObject>(jsonString); string values = appSettings["Values"].ToString();
any help?
*Edit I'm trying to edit values section for local.settings.json file for azure app function in Visual Studio.
-
simple controller index action says "value"
I've seen this in other controllers, but am now seeing it on stripped-down simple examples.
public class EricController : Controller { // GET: Eric public ActionResult Index() { return View(); } }
I have a view (yeah, this is it):
<h2>Index</h2>
My routes:
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
When I go to https://localhost:44389/eric , I get the below, and the debugger is not firing on the Index() method. If I type https://localhost:44389/eric/index, the method is triggered and the view displays as normal.
A) What's up with the "value" getting written to the screen?
B) Why is my default action not being fired?
Also, I recently upgraded to 2.0.7 of Microsoft.AspNetCore.All
-
How do i correctly loop through the my list to display the information using Razor?
I have been struggling to loop through my private static List in my HomeController to display in such a way it shows a list of both students and personnel. Below is an example of what my loop should look like.
[Student] Name:John Surname:Greenberg Email: 123@123 Cellphone:123456789 Age: 20
[Personnel] Name:Rose Surname:Marry Email: email@email Cellphone:123456789 WorkerType: Permanent Degree: BED Education
[Student] Name:Chaz Surname:Brown Email: chazz@gmail.com Cellphone:123456789 Age: 30
Please help me loop properly and Below is my ContestantView i tried coding
@model List<Assignment9_u14333393.Models.ContestantViewModel> <div style="width:100%;height:auto; background-color:brown; padding-top:10px; padding-bottom:10px;"> <h2 style="text-align:center; color:white;">List of Contestants</h2> </div> . <div class="members" > <table> @foreach (var temp in Model) { <div class="member"> [@temp.MemberType] Name:@temp.Name Surname:@temp.Surname Email: @temp.Email Cellphone:@temp.CellPhone </div> } </table> </div>
For additional information I also have three models (StudentViewModel, PersonnelViewModel and ContestantViewModel). ContestantViewModel is my parent class and StudentViewModel and PersonnelViewModel are my classes which have inherited data members and properties for the parent class.
1st Model
public class ContestantViewModel { //Data members private string mName; private string mSurname; private string mCellPhone; private string mEmail; private string mMemberType; //Defeaut Constructor public ContestantViewModel() { mName = "NoName"; mSurname = "NoSurname"; mCellPhone = "NoCellNumber"; mEmail = "NoEmail"; mMemberType = "NoMemberType"; } //Constructor public ContestantViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType) { mName = Name; mSurname = Surname; mCellPhone = CellPhone; mEmail = Email; mMemberType = MemberType; } //Properties public string Name { get { return mName; } set { mName = value; } } public string Surname { get { return mSurname; } set { mSurname = value; } } public string CellPhone { get { return mCellPhone; } set { mCellPhone = value; } } public string Email { get { return mEmail; } set {mEmail = value; } } public string MemberType { get; set; } }
2rd Model
public class PersonnelViewModel : ContestantViewModel { private string mWorkerType; private string mDegree; public PersonnelViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType, string WorkerType, string Degree) : base (Name,Surname,CellPhone,Email, MemberType) { mWorkerType = WorkerType; mDegree = Degree; } public PersonnelViewModel() { mWorkerType = "NoWorkerType"; mDegree = "NoDegree"; } public string WorkerType { get { return mWorkerType;} set { mWorkerType = value; } } public string Degree { get { return mDegree; } set { mDegree = value; } } }
3rd Model
public class StudentViewModel : ContestantViewModel { //Data members private int mAge; //D Constructor public StudentViewModel() { mAge = 0; } //Constructor public StudentViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType, int Age) : base(Name, Surname, CellPhone, Email, MemberType) { mAge = Age; } //properties public int Age { get { return mAge; } set { mAge = value; } } }
and this is my controller
public class HomeController : Controller { // list to hold all my new members private static List<ContestantViewModel> List = new List<ContestantViewModel>(); // GET: Home public ActionResult Index() { return View(); } // GET: Signup public ActionResult Signup(string Name, string Surname, string Email, string Cellphone, string MemberType, int Age,string WorkerType,string Degree) { StudentViewModel Stundent = new StudentViewModel(); PersonnelViewModel Personnel = new PersonnelViewModel(); if (MemberType == "Student") { //creates instance Stundent.Name = Name; Stundent.Surname = Surname; Stundent.Email = Email; Stundent.CellPhone = Cellphone; Stundent.MemberType = MemberType; Stundent.Age = Age; // Add data to list List.Add(Stundent); } else { //creates instance Personnel.Name = Name; Personnel.Surname = Surname; Personnel.Email = Email; Personnel.CellPhone = Cellphone; Personnel.MemberType = MemberType; Personnel.WorkerType = WorkerType; Personnel.Degree = Degree; // Add data to list List.Add(Personnel); } return View(List); } }
-
Not working jQuery ajax to insert data into the database in ASP.NET MVC 5
I can't figure out what error I have in my code. I have checked carefully and tried to insert data into a SQL Server database. But every time it shows "Internal server error" while submitting the form. Please help me to figure out. Thanks
Here is my code..
Database table:
CREATE TABLE [dbo].[Doctor] ( [DoctorID] INT IDENTITY (1, 1) NOT NULL, [DoctorCardID] AS ('DOC' + RIGHT('000' + CONVERT (VARCHAR (3), [DoctorID]), (3))), [DoctorName] VARCHAR(50) NOT NULL, [Gender] VARCHAR(20) NOT NULL, [ContactNumber] VARCHAR(11) NOT NULL, [DoctorAvatar] VARCHAR(500) NULL, [Dob] DATE NULL, [Address] VARCHAR(50) NULL, [City] VARCHAR(50) NULL, [ZipCode] NCHAR(10) NULL, [QualificationID] INT NULL, [SpecialityID] INT NULL, [JoiningDate] DATETIME NOT NULL, [AddeddDate] DATE NULL, [IsActive] BIT DEFAULT ((1)) NULL, PRIMARY KEY CLUSTERED ([DoctorID] ASC), FOREIGN KEY ([QualificationID]) REFERENCES [dbo].[Qualification] ([QualificationID]), FOREIGN KEY ([SpecialityID]) REFERENCES [dbo].[Speciality] ([SpecialityID]) );
Jquery and Ajax code:
$('#doctor-submit').click(function(e) { e.preventDefault(); var data = JSON.stringify({ DoctorName: $('#DoctorName').val(), Gender: $('#Gender').val(), ContactNumber: $('#ContactNumber').val(), Dob: $('#Dob').val(), Address: $('#Address').val(), City: $('#City').val(), ZipCode: $('#ZipCode').val(), QualificationID: $('#QualificationID').val(), SpecialityID: $('#SpecialityID').val(), JoiningDate: $('#JoiningDate').val(), AddeddDate: $('#AddeddDate').val(), IsActive: $('#IsActive').val() }); $.ajax({ url: "@Url.Action("Create", "Doctor")", type: "POST", data: data, processData : false, contentType: "application/json; charset=utf-8", dataType:"json", cache:false, success: function (response) { $('#show-success').show(); } }); });
ASP.NET MVC form:
<form id="DoctorForm" enctype="multipart/form-data"> @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Doctor</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="row"> <div class="col-md-6"> <div class="form-group"> @Html.LabelFor(model => model.DoctorName, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.DoctorName, new { htmlAttributes = new { @class = "form-control", @id = "DoctorName" } }) @Html.ValidationMessageFor(model => model.DoctorName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control", @id = "Gender" } }) @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { @class = "form-control", @id = "ContactNumber" } }) @Html.ValidationMessageFor(model => model.ContactNumber, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Dob, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.Dob, new { htmlAttributes = new { @class = "form-control", @id = "Dob" } }) @Html.ValidationMessageFor(model => model.Dob, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control", @id = "Address" } }) @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control", @id = "City" } }) @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control", @id = "ZipCode" } }) @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.QualificationID, "QualificationID", htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.DropDownList("QualificationID", null, htmlAttributes: new { @class = "form-control", @id = "QualificationID" }) @Html.ValidationMessageFor(model => model.QualificationID, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.SpecialityID, "SpecialityID", htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.DropDownList("SpecialityID", null, htmlAttributes: new { @class = "form-control", @id = "SpecialityID" }) @Html.ValidationMessageFor(model => model.SpecialityID, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.JoiningDate, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { @class = "form-control", @id = "JoiningDate" } }) @Html.ValidationMessageFor(model => model.JoiningDate, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.AddeddDate, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @Html.EditorFor(model => model.AddeddDate, new { htmlAttributes = new { @class = "form-control", @id = "AddeddDate" } }) @Html.ValidationMessageFor(model => model.AddeddDate, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> <div class="checkbox"> @Html.EditorFor(model => model.IsActive, new { @id = "IsActive" }) @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input id="doctor-submit" type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> <div class="col-md-3"> <div class="form-group"> <div class="col-md-12"> <img src="~/Content/images/man.jpg" id="processImage" class="process-image img-responsive" /> <div class="upload-box"> <input id="imageFile" name="ImageUpload" type="file" accept="image/jpeg, image/png" alt="Photo" class="image-file" /> <div class="upload-icon"> <i class="menu-icon fa fa-upload"></i> Upload </div> </div> </div> </div> </div> </div> </div> </form> <div id="show-success" class="success-save alert alert-block alert-success"> <button type="button" class="close" data-dismiss="alert"> <i class="ace-icon fa fa-times"></i> </button> <p> <strong> <i class="ace-icon fa fa-check"></i> Well done! </strong> Doctor Save successfully! </p> </div> <div> @Html.ActionLink("Back to List", "Index") </div>
Controller code:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create( Doctor doctor) { if (ModelState.IsValid) { if (doctor.ImageUpload != null) { string filename = Path.GetFileNameWithoutExtension(doctor.ImageUpload.FileName); string extension = Path.GetExtension(doctor.ImageUpload.FileName); filename = filename + DateTime.Now.ToString("yymmssfff") + extension; doctor.DoctorAvatar = "~/Content/images/DoctorsImg/" + filename; doctor.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Content/images/DoctorsImg"), filename)); } db.Doctors.Add(doctor); db.SaveChanges(); return RedirectToAction("Index", "Doctor"); } ViewBag.QualificationID = new SelectList(db.Qualifications, "QualificationID", "QualificationName", doctor.QualificationID); ViewBag.SpecialityID = new SelectList(db.Specialities, "SpecialityID", "SpecialityTag", doctor.SpecialityID); return Json(new { success = true }); }