mvc getting and sending data from dropdown and datetimepicker - asp.net-mvc

hello everyone I have a question. I have a form which consist of dropdown textbox and datetimepicker. I can fill my dropdown from my model but I cannot post the data to the database. Here are my codes
My Controller codes this is where the data selected and shown in view
public ActionResult orderProduct()
{
Repository<OrderProduct> _ro = new Repository<OrderProduct>();
IEnumerable<OrderProduct> _orderProduct = _ro.All().OrderByDescending(o => o.id);
return View(_orderProduct);
}
I am filling the dropdownlist from database
public ActionResult addOrderProduct()
{
/*
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<Workshop> _workshop = _rw.All().OrderByDescending(o => o.id);
IEnumerable<SelectListItem> _selectList = from w in _workshop
select new SelectListItem {
Text = w.name,
Value = w.id.ToString()
};
*/
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<SelectListItem> _workshopSelectListItem = _rw.All().AsEnumerable().Select(s =>
new SelectListItem {
Text = s.name, Value=s.id.ToString()
});
ViewData["dropdown"] = _workshopSelectListItem;
return View();
}
here I am trying to post my data to the database. I cannot select data from dropdown and datetimepicker also I cannot post this data by writing manually.
public ActionResult orderProductAdd(int adet, float cmt)
{
Repository<OrderProduct> _rp = new Repository<OrderProduct>();
OrderProduct _orderProduct = new OrderProduct { workshopId = 1, orderId = 1, value = adet, shipDate = new DateTime(2005, 02, 01), cmt = cmt };
return RedirectToAction("orderProduct");
}
this is my model
[Table("OrderProduct")]
public class OrderProduct
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public int orderId { get; set; }
[ForeignKey("orderId")]
public virtual Order order { get; set; }
public int workshopId { get; set; }
[ForeignKey("workshopId")]
public virtual Workshop workshop { get; set; }
public int value { get; set; }
public float cmt { get; set; }
public DateTime shipDate { get; set; }
/*
[id]
,[orderId]
,[workshopId]
,[value]
,[cmt]
,[shipDate]
*/
}
and also this is my view "addOrderProduct"
<form action="/Order/orderProductAdd" class="form-horizontal">
<div class="control-group">
<label class="control-label">Atölye Seçiniz</label>
<div class="controls">
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],"secim yapınız", new { #class = "span6 chosen" })
#*<select class="span6 chosen" data-placeholder="Choose a Category" tabindex="1">
<option value=""></option>
<option value="Category 1">A1</option>
<option value="Category 2">A2</option>
<option value="Category 3">A3</option>
<option value="Category 4">A4</option>
</select>*#
</div>
</div>
<div class="control-group">
<label class="control-label">Adet Giriniz</label>
<div class="controls">
<input type="text" class="span6 " name="adet" />
<span class="help-inline">Sadece sayı giriniz</span>
</div>
</div>
<div class="control-group last">
<label class="control-label">İhracat Tarihi</label>
<div class="controls">
<div id="ui_date_picker_inline"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">Cmt</label>
<div class="controls">
<input type="text" class="span6 " name="cmt" />
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Onayla</button>
#*<button type="button" class="btn">Cancel</button>*#
</div>
</form>
How can I solve this ? Thank you.

The first argument in the DDL (below) is the assigned parameter being passed back to the server. When you call the action you're not passing the parameter dropdown. You're only calling int adet, float cmt but not a parameter called dropdown
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],
"secim yapınız", new { #class = "span6 chosen" })
So update your code to something like the one below:
public ActionResult orderProductAdd(int adet, float cmt, string dropdown){
// DO SOMETHING HERE
}
I can't see the input control which is being constructed for the DATETIME part of your query, however it will be similar to the above. Ensure the name of the INPUT matches the parameters being passed back to the server.

Related

EF Core ModelSate Invalid because form is passing foreign key name and value attributes

Very new to MVC Core and C# and just as I think I'm getting the hang of something there's a new curve ball. I have a form which is based on a model which has a foreign key. When I submit the form to the controller the modelState is invalid because the form is passing something back which isn't in the model it is based on. Here is the model:
public partial class Agreement
{
public Agreement()
{
AgreementAmendments = new HashSet<AgreementAmendment>();
Bundles = new HashSet<Bundle>();
Invoices = new HashSet<Invoice>();
}
public int Id { get; set; }
public int OrgId { get; set; }
public string AgreementNumber { get; set; } = null!;
public string? IrespondReference { get; set; }
public string? DocumentLink { get; set; }
public virtual Organization Org { get; set; }
public virtual ICollection<AgreementAmendment> AgreementAmendments { get; set; }
public virtual ICollection<Bundle> Bundles { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
}
This is the Get Create Action Method:
public IActionResult Create()
{
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "ShortName");
return View();
}
This is the form:
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrgId" class="control-label">Organization</label>
<select asp-for="OrgId" class ="form-control" asp-items="ViewBag.OrgId"></select>
</div>
<div class="form-group">
<label asp-for="AgreementNumber" class="control-label">Agreement Number</label>
<input asp-for="AgreementNumber" class="form-control" />
<span asp-validation-for="AgreementNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="IrespondReference" class="control-label">Internal Reference</label>
<input asp-for="IrespondReference" class="form-control" />
<span asp-validation-for="IrespondReference" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DocumentLink" class="control-label">Document Link</label>
<input asp-for="DocumentLink" class="form-control" />
<span asp-validation-for="DocumentLink" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
And this is the HttpPost Create Action Method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("OrgId,AgreementNumber,IrespondReference,DocumentLink")] Agreement agreement)
{
if (ModelState.IsValid)
{
_context.Add(agreement);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "Id", agreement.OrgId);
return View();
}
When I look at the results of the ModelState it shows an error with the Org Key but as far as I can see the form should just be returning the OrgId as per the model. Can someone please let me know where I am going wrong.
Created a View Model for Agreements to handle the form input and then passed that to the base Agreement Model which seems like unnecessary work. Why can't EF Core handle this stuff without having to constantly build View Models just because there is a foreign key?
Anyway, this is the final HttpPost code for others who run into the same issue:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(AgreementWriteViewModel newagreement)
{
if (ModelState.IsValid)
{
var model = new Agreement
{
OrgId = newagreement.OrgId,
AgreementNumber = newagreement.AgreementNumber,
IrespondReference = newagreement.IrespondReference,
DocumentLink = newagreement.DocumentLink,
};
_context.Add(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "ShortName", newagreement.OrgId);
return View();
}

How to post several photos and several text related to each other to the controller

enter image description hereI want to post several photos and several texts related to each other to the controller.what should I do? My form is an Edit Form and I stored all the pictures and taxes separately. but now in Edit Form, I have to send them both together to the controller.
EditTempleViewModel
public class EditTempleViewModel
{
public string Date { get; set; }
public string Title { get; set; }
public string KeyWord { get; set; }
public int Pattern { get; set; }
public int Category { get; set; }
}
SectionViewModel
public class SectionViewModel
{
public int Id { get; set; }
public int PostId { get; set; }
public string Title { get; set; }
public List<string> Text { get; set; }
public IFormFileCollection Image { get; set; }
public string Pic { get; set; }
}
Form
#using Blogger.Models.BlogViewModels
#model EditTempleViewModel
<form id="editForm" enctype="multipart/form-data">
<div class="form-group">
<input asp-for="Title" type="text" class="form-control formClass" id="Title" placeholder="">
</div>
<div class="form-group">
<select asp-for="Category" asp-items="#ViewBag.Category" class="form-control formClass" id="Category">
<option value="" disabled selected>Select group</option>
</select>
</div>
<div class="form-group">
<label asp-for="Pattern"></label>
<select asp-for="Pattern" asp-items="#ViewBag.Pattern" class="form-control formClass ">
<option value="" disabled selected>select</option>
</select>
</div>
<div class="form-group div-textarea" id="inputTextarea">
<label asp-for="KeyWord"></label>
<textarea asp-for="KeyWord" class="form-control formClass" id="KeyWord" rows="1"></textarea>
</div>
<div id="c">
#foreach (var item in Model.sections)
{
<div class="form-group div-textarea" id="inputTextarea">
<label asp-for="#item.Text"></label>
<textarea name="Text" class="form-control formClass txtaraeClass" rows="3">#item.Text</textarea>
</div>
<div class="form-group div-img" id="inputImg">
<div class="custom-file">
<label class="custom-file-label" for="Image">Upload</label>
<input name="Image" type="file" class="custom-file-input formClass fileU" id="Image" multiple>
</div>
</div>
}
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btnEdit">submit</button>
</div>
</form>
Script
$(".btnEdit").click(function (evt) {
evt.preventDefault();
var fileupload = $(".fileU").get();
var files = fileupload;
let myfiles = []
for (var i = 0; i < files.length; i++) {
myfiles.push(files[i]);
}
var data = new FormData();
data.append("Title", $('#Title').val());
data.append("Category", $('#Category').val());
data.append("Pattern", $('#Pattern').val());
data.append("KeyWord", $('#KeyWord').val());
data.append("files", myfiles)
let json =
{
"Title": $('#Title').val(),
"Category": $('#Category').val(),
"Pattern": $('#Pattern').val(),
"KeyWord": $('#KeyWord').val(),
files: data,
images: data
}
var frm = $('#editForm').serialize();
$.ajax({
type: "post",
url: "/Home/Uploadfilesajax",
contentType :false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("there was error uploading files!");
}
});
});
Cotroller
[HttpPost]
public async Task<IActionResult> UploadFilesAjax(EditTemple model, IFormCollection files)
{
}
I have Null data in both model and files
enter image description here

How do I get my view to show my database table

i'm new to ASP.net. I am trying to figure out how to get my Edit/Display pages working properly for a multiselect listbox.
My create works fine, and saves to my database, but I cannot figure out how to return to the edit page, and still see the values selected.
Hopes this makes sense.
Here is the code that I have for the create method. The record saves fine in both tables, but I am having trouble getting the values from my Options table.
I want to try to make the Edit view look like the Create View
Controller
[HttpPost]
public IActionResult Create(MusicViewModel model)
{
if(ModelState.IsValid)
{
var album = new Music();
album.Album = model.Album;
album.Artist = model.Artist;
album.Label = model.Label;
album.Review = model.Review;
album.ReleaseDate = model.ReleaseDate;
foreach(Types type in model.Options)
{var opt = new Options();
opt.Music = album;
opt.Types = type;
_musicData.AddOptions(opt);
}
_musicData.Add(album);
_musicData.Commit();
return RedirectToAction("Details", new { id = album.MusicID });
}
return View();
}
Music.cs
public enum Types
{
Spotify,
Groove,
CD,
Vinyl,
Pandora
}
public class Music
{
public int MusicID { get; set; }
[Required]
[MaxLength(50),MinLength(5)]
public string Artist { get; set; }
[Required, MinLength(5)]
public string Album { get; set; }
public int Rating { get; set; }
public Label Label { get; set; }
[DataType(DataType.Date)]
[Display(Name ="Release Date")]
public DateTime ReleaseDate { get; set; }
public string Review { get; set; }
public List<Options> Options { get; set; }
}
public class Options
{
public int OptionsID { get; set; }
public Types Types { get; set; }
public int MusicID { get; set; }
public Music Music { get; set; }
}
public class MusicDbContext:DbContext
{
public DbSet<Music> Albums { get; set; }
public DbSet<Options> Options { get; set; }
}
View
#model Music
....
<form asp-action="Create" method="post">
<div class="row">
<div class="col-md-3 col-md-offset-2">
<fieldset class="form-group">
<label asp-for="Artist"></label>
<input class="form-control" asp-for="Artist" />
<span asp-validation-for="Artist" class="alert"></span>
</fieldset>
</div>
<div class="col-md-3">
<fieldset class="form-group">
<label asp-for="Album"></label>
<input class="form-control" asp-for="Album" />
<span asp-validation-for="Album" class="alert"></span>
</fieldset>
</div>
<div class="col-md-3">
<label asp-for="Label"></label>
#Html.DropDownList("Label", Html.GetEnumSelectList(typeof(Label)), "-------", new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-2">
<fieldset class="form-group">
<label asp-for="Options"></label>
<select multiple class="form-control" asp-for="Options"
asp-items="#Html.GetEnumSelectList(typeof(Types))"></select>
</fieldset>
</div>
<div class="col-md-3">
<fieldset class="form-group">
<label asp-for="ReleaseDate"></label>
<input type="text" asp-for="ReleaseDate" class="DateBox form-control" />
<span asp-validation-for="ReleaseDate" class="alert"></span>
</fieldset>
</div>
</div>
<div class="col-md-offset-3"><input class="btn btn-info" type="submit" value="Submit" /></div>
</form>
I figured it out, probably not the most efficient way, but at least the code works
[HttpPost]
public IActionResult Edit(int id,MusicViewModel model)
{
var album = _musicData.GetM(id);
if (album != null && ModelState.IsValid)
{
album.Album = model.Album;
album.Artist = model.Artist;
album.Label = model.Label;
album.Review = model.Review;
album.ReleaseDate = model.ReleaseDate;
_musicData.RemoveOptions(id);
foreach (Types type in model.Options)
{
var opt = new Options();
opt.MusicID = id;
opt.Types = type;
_musicData.AddOptions(opt);
}
_musicData.Commit();
return RedirectToAction("Details",id);
}
return View(album);
}

how can i assign value to textbox in MVC - Sharepoint Provider-hosted

I want to get and assign value to my textbox from controller.
here is my textbox:
<input type="text" class="form-control" id="RegardingTo" name="RegardingTo" value="??????"/>
then i want to get the value from this action.
public ActionResult Edit(int? RequestID)
{
if (RequestID <= 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var ReqID = db.usp_RequestGetDetails(RequestID);
if (ReqID == null)
{
return HttpNotFound();
}
return View();
}
please help :)
Yes you can assign value to the textbox using Model, First of all create a model then link that model with your view. And In Controller assign the value to model and return to the view.
Or At runtime if you want to assign the value to your text box then you can use Ajax call to your controller and get the value.
Please revert in case of any query.
See what i am doing to do the same, Make a custom model with your relevant fields, then assign values to them in controller, and pass this values to View, And that's it. :)
Custom Model
public partial class QuoteParameter
{
public Nullable<System.DateTime> TripStartDateLimit { get; set; }
public Nullable<System.DateTime> TripEndDateLimit { get; set; }
public int PolicyId { get; set; }
}
Controller
public ActionResult Index()
{
QuoteParameter quote = new QuoteParameter();
quote.TripEndDateLimit = DateTime.Now;
quote.TripEndDateLimit = DateTime.Now;
quote.PolicyId = 5;
return View(quote);
}
View
#model EHIC.Models.Models.QuoteParameter
By Razor syntax
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip Start Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripStartDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy StartDate Limit", #required = true })
</div>
</div>
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip End Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripEndDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy EndDate Limit", #required = true })
</div>
</div>
By HTML Code
<input type="text" class="form-control" id="TripStartDateLimit" name="TripStartDateLimit" value="#Model.TripStartDateLimit"/>
<input type="text" class="form-control" id="TripEndDateLimit" name="TripEndDateLimit" value="#Model.TripEndDateLimit"/>
EDIT
By Click on this button you can send the PolicyId(as an example) to controller, and then you can do whatever you want there..!!!
<a href='../../controller/Edit?PolicyId=#Models.PolicyId'>
<span title='Edit'></span>
</a>
#Html.ActionLink("Edit","Edit", new { id = item.RequestID })
You can find the PolicyId which you sent from the Edit Page..
public ActionResult Edit(int id)
{
//Get your data from Store_procedure..
return View();
}

How get values into a select box from sql server

Can anyone help me to populate a select box with values from sql server. I'm using MVC ASP.NET, I have a form, that is from a table X, one of it columns it's called Location and brings the city where it's from, but i have all the cities in another table Y, and want to insert the select inside that form. How should i enter the code inside the model/controller.
Here is how i set the form for table X:
Model:
public int Insertar(Inmueble inmueble)
{
SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");
conexion.Open();
SqlCommand comando = conexion.CreateCommand();
comando.CommandText = "insert into Inmuebles (Titulo, Descripcion, Ambientes, Precio, Localidad, Tags, Usuario)" +
"output inserted.Id values (#Titulo, #Descripcion, #Ambientes, #Precio, #Localidad, #Tags, #Usuario)";
comando.Parameters.AddWithValue("#Titulo", inmueble.Titulo);
comando.Parameters.AddWithValue("#Descripcion", inmueble.Descripcion);
comando.Parameters.AddWithValue("#Ambientes", inmueble.Ambientes);
comando.Parameters.AddWithValue("#Precio", inmueble.Precio);
comando.Parameters.AddWithValue("#Localidad", inmueble.Localidad);
comando.Parameters.AddWithValue("#Tags", inmueble.Tags);
comando.Parameters.AddWithValue("#Usuario", inmueble.Usuario);
int nuevoId = (int)comando.ExecuteScalar();
inmueble.Id = nuevoId;
conexion.Close();
return nuevoId;
}
This is my controller:
[HttpPost]
public ActionResult Create(FormCollection formulario)
{
string Titulo = formulario["Titulo"];
string Descripcion = formulario["Descripcion"];
int Precio = Convert.ToInt32(formulario["Precio"]);
int Ambientes = Convert.ToInt32(formulario["Ambientes"]);
int Localidad = Convert.ToInt32(formulario["Localidad"]);
string Usuario = formulario["Usuario"];
string Tags = formulario["Tags"];
Inmueble inmueble = new Inmueble();
inmueble.Titulo = Titulo;
inmueble.Localidad = Localidad;
inmueble.Precio = Precio;
inmueble.Ambientes = Ambientes;
inmueble.Usuario = Usuario;
inmueble.Descripcion = Descripcion;
inmueble.Tags = Tags;
InmueblesManager managerInmuebles = new InmueblesManager();
int idInsertado = managerInmuebles.Insertar(inmueble);
if (Request.Files.Count > 0 &&
Request.Files[0].ContentLength > 0) //para validar que vino el archivo
{
string rutaFinal = Server.MapPath("~/Content/imagenes/inmuebles/" + idInsertado + ".jpg");
Request.Files[0].SaveAs(rutaFinal);
}
return RedirectToAction("Index", "Home");
}
And this is how it looks at html code the form:
<form action="#Url.Action("Create", "Inmuebles")" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="Titulo">Titulo</label>
<input id="Titulo" name="Titulo" type="text" placeholder="Titulo" />
</div>
<div class="form-group">
<label for="Localidad">Localidad</label>
<input id="Localidad" name="Localidad" type="text" placeholder="Localidad del Inmueble" />
</div>
<div class="form-group">
<label for="Descripcion">Descripcion</label>
<textarea id="Descripcion" name="Descripcion" placeholder="Ingresa aqui la descripcion"></textarea>
</div>
<div class="form-group">
<label for="Precio">Precio</label>
<input type="number" id="Precio" name="Precio" />
</div>
<div class="form-group">
<label for="Ambientes">Ambientes</label>
<input type="number" id="Ambientes" name="Ambientes" />
</div>
<div class="form-group">
<label for="Tags">Tags</label>
<input id="Tags" name="Tags" type="text" placeholder="Tags para una busqueda mas rapida" />
</div>
<div>
<input type="hidden" value="#(((ja_era.Models.Usuario)Session["usuario"]).NombreDeUsuario)" name="Usuario" />
</div>
<div class="form-group">
<label for="imagen">Imagen</label>
<input id="imagen" name="imagen" type="file" />
</div>
<input type="submit" value="Guardar" />
You haven't even attempted anything, which is kind of a no-no around these parts. I will give you a bit of general guidance, though. First, use a view model to pass data to/from the view. You should pretty much never take a FormCollection.
public class InmuebleViewModel
{
public string Titulo { get; set; }
public int Localidad { get; set; }
public int Precio { get; set; }
public int Ambientes { get; set; }
public string Usuario { get; set; }
public string Descripcion { get; set; }
public string Tags { get; set; }
}
Then, your get action should pass this to your view:
public ActionResult Create()
{
var model = new InmuebleViewModel();
return View(model);
}
Your view should use this model and utilize the HTML helpers to generate your inputs:
#model Namespace.To.InmuebleViewModel
...
<div class="form-group">
#Html.LabelFor(m => m.Titulo)
#Html.EditorFor(m => m.Titulo, new { htmlAttributes = new { placeholder = "Titulo" } })
</div>
...
Finally, your post action should take this view model as a param:
[HttpPost]
public ActionResult Create(InmuebleViewModel model)
{
...
}
That's all just standard MVC best practice stuff. However, using the view model also gives you the ability to have a select list on it:
public IEnumerable<SelectListItem> FooOptions { get; set; }
Which you can then use in your view:
#Html.DropDownListFor(m => m.Foo, Model.FooOptions)
You just need to populate that property in both your get and post actions. For that, I recommend adding a protected method to your controller that both can call to keep it dry:
protected void PopulateFooOptions(InmeubleViewModel model)
{
// retrieve you options from the database, selected into an enumerable of `SelectListItem`
model.FooOptions = options;
}
Then, both your get and post Create actions call this before returning the view:
PopulateFooOptions(model);
return View(model);

Resources