Passing Data from View to Controller failed in asp.net mvc - c#

I want to pass data from view to controller but it always returns 0 and I don't know why.
I have to verify if the entred code is the same as passed in parametre of ActionResult Sortie() but I can't get the value entred in view.
View:
#model ViewModel.DemandeViewModel
#{
ViewBag.Title = "Sortie";
}
<div class="col-xs-12">
<div class="box">
<h2>Sortie Gabarit</h2>
#using (Html.BeginForm("Sortie", "Demandes", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CodeBarre)
#ViewBag.error
#Html.ValidationMessage("error_msg")
<div class="form-group">
#Html.LabelFor(model => model.CodeBarre, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { #class = "form-control", #name = "codeB" } })
#Html.ValidationMessageFor(model => model.CodeBarre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Sortie" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
</div>
Controller:
//Get Sortie
public ActionResult Sortie(Int64 id)
{
TempData["codebarre"] = id;
return View();
}
//Post Sortie
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Sortie()
{
var mvtrepository = new MvtRepository(db);
var c = Request.Form["codeB"];
if (Convert.ToInt64(TempData["codebarre"]) == Convert.ToInt64(c))
{
var mvtInsert = mvtrepository.InsertMvt(DateTime.Now, Convert.ToInt64(TempData["codebarre"]), 2);
return RedirectToAction("Traitement");
}
else
{
return View("Error");
}
}
Help please and thank you.

Do not access the Request.Form directly. Instead, your POST action should accept the ViewModel as parameter.
[HttpPost]
public ActionResult Sortie(ViewModel.DemandeViewModel postData) {
int c = postData.CodeBarre; // assuming CodeBarre is an int in the ViewModel
if ((int)TempData["codebarre"] == c) {
// ...
}
// ...
}
Also in your View, let MVC set the name attribute so the ViewModel can be bound correctly by the ModelBinder.
#Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { #class = "form-control" } })
Because you have an Editor input for the CodeBarre, you do not need another hidden input for it. Remove the line
#Html.HiddenFor(model => model.CodeBarre)

Related

How to pass dropDown list Selected data to another table and update that table in asp.Net MVC

The control class saves the input data into Invoice table.
This is my control class
public ActionResult UpdateInvoice()
{ var getProduct = db.InventoryTbs.ToList();
SelectList list = new SelectList(getProduct, "PId", "PName", "PPrice");
ViewBag.Product = list;
return View();
}
[HttpPost]
public ActionResult UpdateInvoice(InvoiceTb idetail)
{
if (Session["User"] == null) // doesn't work
{
return RedirectToAction("Login");
}
else
{
try
{
db.InvoiceTbs.Add(idetail);
db.SaveChanges();
return RedirectToAction("ShowInvoice");
}
catch
{
return View();
}
}
}
This is my UpdateInvoice.cshtml. Here if I input the Lquantity and Bill value gets saved into the Invoice table.
I have created dropdown list that shows item present in another table(inventory). But it doesnot add to Invoice table.
After entering the quantity I want it to calculate the bill taking selected product price from inventory table
I have tried Json and some other ways but finding no luck.
#model TallyBook_Store_Management_System.Models.InvoiceTb
#{
ViewBag.Title = "UpdateInvoice";
var product = ViewBag.Product;
}
<h2>UpdateInvoice</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>InvoiceTb</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ListName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList( "Product", "Select")
#Html.ValidationMessageFor(model => model.ListName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LQuantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LQuantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LQuantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bill, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bill, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bill, "", 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>
I have solved the issue by passing drop down list selected data from view to controller. Then I have updated the specific database table in Controller.
If there is another efficient or good ways Please do share, I would like to learn more better approaches.

Is there a way to use Controller and View with different name yet still able to display error attribute messages?

I have a View that display a form of field to create new data, then send those data to another controller with different name to execute. The problem is by having different name, I can't display error messages for input field since they don't interact throught same view. I have tried sending Object model back to the view.
My Controller and View:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult CreateBookHTMLHEPER(Book book)
{
if (book.bookTitle != "" && book.author != null)
{
_db.Books.Add(book);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Create", book);
}
}
My cshtml:
#using (Html.BeginForm("CreateBookHTMLHEPER", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="border container" style="padding:30px;">
<div class="hidden">
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
</div>
<div class="form-group row">
<div class="col-3">
Book Title
</div>
<div class="col-6">
#if (Model != null)
{
#Html.EditorFor(model => model.bookTitle, new { #class = "form-control", #value = #Model.bookTitle })
}
else
{
#Html.EditorFor(model => model.bookTitle, new { #class = "form-control"})
}
#Html.ValidationMessageFor(model => model.bookTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-3">
Author
</div>
<div class="col-6">
#if (Model != null)
{
#Html.EditorFor(model => model.author, new { #class = "form-control", #value = #Model.author })
}
else
{
#Html.EditorFor(model => model.author, new { #class = "form-control" })
}
#Html.ValidationMessageFor(model => model.author, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<button type="submit" class="btn btn-primary form-control">
Create
</button>
</div>
<div class="col-3">
Back To List
</div>
</div>
</div>
}

html helper don't get values back from controller after ajax.beginform

I have a ajax.beginform that I have to upload a file and then in the view I have hidden for the path of the file that have been
saved in the server.
The problem is that the value of the path doesn't return to the view after the the post call.
I am returning new partial view with the errors and the value don't
coming
please help me
post method from controller that return partial view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
bool sociook = false;
socio.StudentId = sStudentId; // bind student id to socio model
socio = SocioDetValid(ref sociook,socio);
// add validation
if (ModelState.IsValid && sociook)
{
socio = SaveSocioModel(socio);
Response.StatusCode = 200;
}
else
Response.StatusCode = 300; // return error to client the model is not valid
return PartialView("~/Views/Student/Socio/SocioDetails.cshtml", socio); // return the partial view of the forn with validation messages
}
Sociodetvalid function that saves the file and add the path to path field:
// bank account validation and save
if (socio.FileBankAccount == null) // if there is no file
{
if (socio.PathBankAccount == null) // check if he upload file already - if not add error message
{
ModelState.AddModelError("FileBankAccount", "חובה לצרף קובץ");
ok = false;
}
}
else // upload new the file
socio.PathBankAccount = Files.SaveFileInServer(socio.FileBankAccount, "BankAccount", sStudentId, socio.PathBankAccount);
the section in view for upload and the hidden for the path string:
<div class="row">
<div class="col-xl-3 col-lg-3 col-md-4 col-12 ">
#Html.LabelFor(model => model.BankStatus, htmlAttributes: new { #class = "control-label col-12" })
#Html.EditorFor(model => model.BankStatus, new { htmlAttributes = new { #class = "form-control must m-1 mt-0" } })
#Html.ValidationMessageFor(model => model.BankStatus, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PathBankAccount)
</div>
<div class="col-xl-3 col-lg-3 col-md-4 col-12">
#Html.LabelFor(model => model.FileBankAccount, htmlAttributes: new { #class = "control-label col-12 must-sign", #for = "" })
<div class="chose-file m-1 mt-0">
#Html.TextBoxFor(model => model.FileBankAccount, new { #class = "form-control must", #type = "file", #accept = "image/jpeg,image/jpg,image/png,application/pdf", #style = "display:none;" })
<label for="FileBankAccount">
<i class="ml-1 material-icons">add_photo_alternate</i>
בחר קובץ
</label>
</div>
#Html.ValidationMessageFor(model => model.FileBankAccount, "", new { #class = "text-danger" })
</div>
#*
<div class="col-xl-3 col-lg-3 col-md-4 col-12" style="display:#(Model.PathBankAccount != null ? "" : "none")">
<label class="control-label col-12" for="">קובץ שמור</label>
<a name="#Model.PathBankAccount" class="btn btn-light btn-file m-1 mt-0">צפייה בקובץ שמור</a>
</div>*#
Thanks for help
Update:
Ajax form code : this is the part of the ajax that in a big view
<fieldset>
#using (Ajax.BeginForm("SaveSocioDetails", "Student", new AjaxOptions { HttpMethod = "POST", OnSuccess = "firstsuccess",OnFailure = "sociodetailsfail", UpdateTargetId="partialsocio" ,LoadingElementId = "div_loading" }, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="partialsocio">
#Html.Action("PartialSocioDetails", "Student", new { SpId = ViewBag.SpId })
</div>
<div id="div_loading" style="display:none;">
<img src="#Url.Content("~/Content/Pic/Spinner.gif")" alt="" />
</div>
<button class="btn btn-primary" type="submit">המשך</button>
}
<input type="button" name="next" class="next action-button bg-primary" hidden value="Next" id="sociodetnext" />
</fieldset>
this is the function of fail and success ajax:
<script>
$(document).ready(function ()
{
});
function firstsuccess() {
console.log('this is ajaxSuccess');
$("#sociodetnext").click();
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(bdata.responseText);
$('#partialsocio').html(bdata.responseText);
}
</script>
In the script that Have returned to the client the value of the string doesn't appear..
Thanks for help

Pass data between several views in MVC applications

I am creating a MVC application and I would like to pass data between views.
Here is my first view:
#model ClassDeclarationsThsesis.Models.AddGroupViewModel
#{
ViewBag.Title = "Add Groups";
}
<h2>Add Groups to subjects</h2>
#foreach (var user in Model.Users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("AddGroup", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create new groups.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
}
#foreach (var subject in Model.Subjects)
{
listItems1.Add(new SelectListItem
{
Text = subject.name,
Value = subject.name,
Selected = true
});
}
#Html.LabelFor(m => m.subject_name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.subject_name, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.qty, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.qty, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
And my controller for this:
public ActionResult AddGroup(AddGroupViewModel model)
{
var entities = new ClassDeclarationsDBEntities1();
var model1 = new AddGroupViewModel();
model1.Subjects = entities.Subjects.ToList();
model1.Users = entities.Users.ToList();
// set your other properties too?
if (ModelState.IsValid)
{
return RedirectToAction("AddGroupsQty", "Account");
}
return View(model1);
}
And what I would like to achieve is to pass chosen item from dropdown list and this qty variable to AddGroupsQty View. How do I do this? In my controller of AddGroupsQty i have just a simple return of view so far.
You can pass the values using querystring.
return RedirectToAction("AddGroupsQty", "Account",
new { qty=model.qty,subject=model.subject_name);
Assuming your AddGroupsQty have 2 parameters to accept the quantity and subject
public ActionResult AddGroupsQty(int qty,string subject)
{
// do something with the parameter
// to do : return something
}
This will make browser to issue a new GET request with the values in query string. If you do not prefer to do that, you can use a server side temporary persistence mecahnism like TempData
TempData["qty"]=model.qty;
TempData["subject"]= model.subject_name;
return RedirectToAction("AddGroupsQty", "Account");
And in your AddGroupsQty action,
public ActionResult AddGroupsQty()
{
int qty=0;
string subjectName=string.Empty;
if(TempData["qty"]!=null)
{
qty = Convert.ToInt32(TempData["qty"]);
}
if(TempData["subject"]!=null)
{
subjectName = TempData["subject"];
}
// Use this as needed
return View();
}
If you want to pass these values from the ADdGroupsQty action to it's view, you can use either a view model or ViewBag/ViewData.

The model item passed into the dictionary is of type 'System.Collections.Generic.List'

I'm new to asp.net and this is my first application.
I'm developing an application that manages insurance requests. The model Request contains a file upload. the addDemand (adds a request)requires a member(adherent) to be logged in. Every time I try to run the addDemande I get the error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mutuelle.Domain.Entities.Demande]', but this dictionary requires a model item of type 'Mutuelle.Domain.Entities.Demande'.
Here's the controller:
public ActionResult AddDemande()
{
Demande demande = new Demande();
return View(demande);
}
[HttpPost]
public ActionResult AddDemande([Bind(Exclude = "fichier")]Demande demande, HttpPostedFileBase fichier)
{
try
{
if (!ModelState.IsValid)
{
return View();
}
else
{
BinaryReader fichierReader = new BinaryReader(fichier.InputStream);
byte[] fichiers = fichierReader.ReadBytes(fichier.ContentLength);
demande.fichier = fichiers;
AdherentDService adherentService = new AdherentDService();
Adherent adherent = (Adherent)Session["logedAd"];
demande.nomBeneficiaire = adherent.nom;
demande.eMailBeneficiaire = adherent.eMail;
demande.beneficiare = adherent;
adherent.listDemandes.Add(demande);
adherentService.Updateadherent(adherent);
demande.beneficiare = adherent;
adherentService.CreateaDemande(demande);
Session.Remove("logedAd");
Session.Add("logedAd", adherent);
return RedirectToAction("Demandes");
}
}
catch
{
return RedirectToAction("Index", "Home");
}
}
And here's the View:
model Mutuelle.Domain.Entities.Demande
#{
ViewBag.Title = "AddDemande";
}
<h2>AddDemande</h2>
#using (Html.BeginForm("AddDemande", "Adherent", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Demande</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Nomrubrique, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nomrubrique)
#Html.ValidationMessageFor(model => model.Nomrubrique)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.fichier, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input style="margin-left:0px;cursor:pointer;" type="file" name="fichier" id="fichier" />
</div>
</div>

Categories