Mvc Save Items From Cascading DropdownList - c#

This is my controller.
public class DokuzasController : Controller
{
schoolEntities se = new schoolEntities();
public ActionResult Index()
{
IEnumerable<DersViewModel> leclist;
HttpResponseMessage responselec = GlobalVariables.LecturesClient.GetAsync("dokuzas").Result;
leclist = responselec.Content.ReadAsAsync<IEnumerable<DersViewModel>>().Result;
return View(leclist);
}
public ActionResult AddOrEdit()
{
List<ders> dersList = se.ders.ToList();
ViewBag.dersList = new SelectList(dersList, "DersID", "Ders1");
return View();
}
public JsonResult GetDersList(int DersID)
{
se.Configuration.ProxyCreationEnabled = false;
List<saat> saatList = se.saat.Where(x => x.DersID == DersID).ToList();
return Json(saatList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel lec)
{
if (lec.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", lec).Result;
TempData["SuccessMessage"] = "Kaydedildi.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + lec.LectureId, lec).Result;
TempData["SuccessMessage"] = "Güncellendi.";
}
return RedirectToAction("Index");
}
}
And this is AddOrEdit part.
#model Mvc.Models.DersViewModel
<div class="container">
<div class="form-group">
#if (ViewBag.dersList != null)
{
#Html.DropDownListFor(model => model.DersID, ViewBag.dersList as SelectList, "--Lecture--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.SaatID, new SelectList(" "), "--Time--", new { #class = "form-control" })
</div>
</div>
#using (Html.BeginForm())
{
<div class="form-group">
<input type="submit" value="Kaydet" class="btn button" />
<input type="reset" value="Sil" class="btn button" />
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#DersID").change(function () {
$.get("/Dokuzas/GetDersList", { DersID: $("#DersID").val() },
function (data) {
$("#SaatID").empty();
$.each(data, function (index, row) {
$("#SaatID").append("<option value='" + row.SaatID + "'>" + row.Saat1 + "</option>");
});
});
});
});
</script>
I create a cascading dropdown list for lecture and time but i cannot save it to the table. When i choose items and select submit button i can submit only null to the table. It did not save what i choose from the dropdownlist. How can i save from my cascading dropdown list to the table?

Your Dropdowns are not inside your Form, so they are not included in the post. Try the below code for your view.
#model Mvc.Models.DersViewModel
#using (Html.BeginForm())
{
<div class="container">
<div class="form-group">
#if (ViewBag.dersList != null)
{
#Html.DropDownListFor(model => model.DersID, ViewBag.dersList as SelectList, "--Lecture--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.SaatID, new SelectList(" "), "--Time--", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Kaydet" class="btn button" />
<input type="reset" value="Sil" class="btn button" />
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#DersID").change(function () {
$.get("/Dokuzas/GetDersList", { DersID: $("#DersID").val() },
function (data) {
$("#SaatID").empty();
$.each(data, function (index, row) {
$("#SaatID").append("<option value='" + row.SaatID + "'>" + row.Saat1 + "</option>");
});
});
});
});
</script>

Related

bind another model to partial view like nested partial view binding

I have a button which add individualSearch partial view and individualSearch partial view also have a add button which adds individualSearcharacteristic partial view in it.
I want to bind BMRTestData model with individualSearch partial so that i can get the characteristic partial view data. So i store that data in IndividualSearch's list public List<Characteristic> Characteristics { get; set; } = new List<Characteristic>();
Please guide me to do same as i am new to .net .
Coding
//TestData(Main View)
#using ABC.Core.Models.DTOs
#model ABC.Core.Models.Api.BMRTestData
#using (Html.BeginForm())
{
<div class="card mb-3">
<h5 class="card-header">Response</h5>
<div class="card-body">
<div class="card-block">
<div class="form-group">
#Html.LabelFor(m => m.CompanyName, "Company Name", new { #class = "form-control-label" })
#Html.TextBoxFor(m => m.CompanyName, null, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.CompanyName)
</div>
<div id="searchindividuals" class="mb-3">
#if (Model?.IndividualSearches != null)
{
for (var i = 0; i < Model?.IndividualSearches.Count; i++)
{
<div class="form-group">
#{ Html.RenderPartial("IndividualSearchPartial", Model.IndividualSearches[i], new ViewDataDictionary()); }
</div>
}
}
</div>
<div class="mb-3">
<button id="add-search-individual" type="button" class="btn btn-success">Add Search Individual</button>
</div>
<button id="add-company-characteristic" type="button" class="btn btn-success">Add Characteristic</button>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
}
#section Scripts
{
function add(element){
var action = ' #Url.Action("NewIndividualSearchCharacteristic", "Blended")';
$.post(action)
.done(function (partialView) {
$(element.previousElementSibling).append(partialView);
});
}
</script>
}
//IndividualSearchPartial
#using (Html.BeginCollectionItem("IndividualSearches"))
{
<div id="individual-details" class="card">
<div class="form-horizontal">
<div class="card-block">
<div class="form-group">
#Html.LabelFor(m => m.SearchPostcode, "Search Post Code", new { #class = "form-control-label" })
#Html.TextBoxFor(m => m.SearchPostcode, null, new { #class = "form-control" })
</div>
</div>
</div>
<div class="card-block">
<div id="Characteristics" class="mb-3">
#if (Model?.Characteristics != null)
{
for (var i = 0; i < Model?.Characteristics.Count; i++)
{
<div class="form-group">
#{ Html.RenderPartial("IndividualSearchCharacterisiticPartial", Model.Characteristics[i], new ViewDataDictionary()); }
#* #Html.EditorFor(m => m.Characteristics);*#
</div>
}
}
</div>
<button id="add-characteristics" onclick="add(this)" type="button" class="btn btn-success">Add Characteristics</button>
</div>
</div>
}
// IndividualSearchCharacterisiticPartial
#model ABC.Core.Models.DTOs.Characteristic
#using (Html.BeginCollectionItem("Characteristics"))
{
<div id="characteristic-details" class="card">
<div class="form-horizontal">
<div class="card-block">
<div class="container">
<div class="row">
<div class="col-*-*">
#Html.LabelFor(m => m.Name, "Name", new { #class = "form-control-label" })
</div>
<div class="col">
#Html.TextBoxFor(m => m.Name, null, new { #class = "form-control" })
</div>
<div class="col-*-*">
#Html.LabelFor(m => m.Value, "Value", new { #class = "form-control-label" })
</div>
<div class="col">
#Html.TextBoxFor(m => m.Value, null, new { #class = "form-control" })
</div>
<div class="col-*-*">
<a id="characteristic-remove" href="#" onclick="removeCharacteristic(this)" class="btn btn-danger pull-right">Remove</a>
</div>
</div>
</div>
</div>
</div>
</div>
}
//IndividualSearch Class
namespace ABC.Core.Models.DTOs.Individual
{
public class IndividualSearch
{
public List<Characteristic> Characteristics { get; set; } = new List<Characteristic>();
}
}
namespace ABC.Core.Models.Api
{
public class BMRTestData : BMRRequest
{
public List<IndividualSearch> IndividualSearches { get; set; } = new List<IndividualSearch>();
}
}
Update
You can add onclick event in Add Search Individual button:
<button id="add-search-individual" type="button" class="btn btn-success" onclick="addSearch(this)">Add Search Individual</button>
Add an action in controller to return IndividualSearchPartial partial view:
[HttpPost]
public ActionResult IndividualSearchCharacteristic()
{
IndividualSearch individualSearch = new IndividualSearch() { };
return PartialView("IndividualSearchPartial", individualSearch);
}
Here is all the js in main view:
#section Scripts
{
<script>
function add(element){
var action = ' #Url.Action("NewIndividualSearchCharacteristic", "Default")';
$.post(action)
.done(function (partialView) {
$(element).parents('#individual-details').find("#Characteristics").append('<div class="form-group">' + partialView + '</div>');
ResetName();
});
}
function addSearch(element){
var action = ' #Url.Action("IndividualSearchCharacteristic", "Default")';
$.post(action)
.done(function (partialView) {
$(element).parents('.mb-3').find('#searchindividuals').append('<div class="form-group search">' + partialView + '</div>');
ResetName();
});
}
function ResetName() {
var index = 0;
$(".search").each(function () {
var nameIndex = 0; var valueIndex = 0;
$(this).find(":input[type='hidden']").each(function () {
$(this).removeAttr("name");
});
$(this).find(":input[type='text']").each(function () {
if ($(this).attr("name").indexOf("Characteristics") > -1 && $(this).attr("name").indexOf("Name") > -1) {
$(this).attr("name", "IndividualSearches[" + index + "].Characteristics[" + nameIndex + "].Name");
nameIndex++;
return;
}
if ($(this).attr("name").indexOf("Characteristics") > -1 && $(this).attr("name").indexOf("Value") > -1) {
$(this).attr("name", "IndividualSearches[" + index + "].Characteristics[" + valueIndex + "].Value");
valueIndex++;
return ;
}
if ($(this).attr("name").indexOf("IndividualSearches") > -1) {
$(this).attr("name", "IndividualSearches[" + index + "].SearchPostcode");
return;
}
});
index++;
})
}
</script>
}
After submit, it will enter into following action to receive BMRTestData data:
[HttpPost]
public IActionResult TestData(BMRTestData bMRTest)
{
return View();
}
Here is the test result:

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

asp.NET mvc, get model list values from view

I am new to mvc and am trying to do something like in the below image (im not using partial views).
I have an IEnumerable property on Model
Like in this image, (i have not enough reputation to show image directly)
but on controller if i put FormCollection as parameter to accepting post method when i process same name fields i get an extra character ',', which might be also used by user...
Any idea....
[EDIT]
My view
#model Models.Question
#{
ViewBag.Title = "Add";
}
<h2>Add</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Question</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SurveyId)
<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.QuestionTypeId, "Question type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.QuestionTypeId, new SelectList(ViewBag.QuestionTypes, "QuestionTypeId", "Name"), new { #class = "form-control col-md-10" })
<button type="button" class="btn btn-default addAnswer hide"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
#Html.ValidationMessageFor(model => model.QuestionTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hide">
#Html.LabelFor(model => model.Answers, "Options", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="allAnswers">
#Html.ValidationMessageFor(model => model.Answers, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sort, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sort, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sort, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mandatory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Mandatory)
#Html.ValidationMessageFor(model => model.Mandatory, "", new { #class = "text-danger" })
</div>
</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", "Question", "Survey", new { id = Model.SurveyId }, null)
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval", "~/Scripts/QuestionAdd.js")
}
Controller
[HttpGet]
public ActionResult Add(long id)
{
var question = new Models.Question();
question.SurveyId = id;
ViewBag.QuestionTypes = BLL.Questions.GetQuestionTypes();
return View(question);
}
[HttpPost]
public ActionResult Add(FormCollection coll)
{
if (ModelState.IsValid)
{
var question = new Models.Question();
question.Name = coll["Name"];
byte qid = 0, sort = 0;
bool mandatory = false;
byte.TryParse(coll["QuestionTypeId"], out qid);
byte.TryParse(coll["Sort"], out sort);
bool.TryParse(coll["Mandatory"], out mandatory);
question.QuestionTypeId = qid;
question.Sort = sort;
question.Mandatory = mandatory;
foreach (var answer in coll["Answers"])
question.Answers.Add(new Models.Answer() { Value = answer + "" });
if (question != null)
{
if (BLL.Questions.Insert(question) != null)
ViewBag.Message = "Successfully inserted";
else
ViewBag.Message = "Insert could not be done";
return RedirectToAction("Index", "Question", new { questionId = question.QuestionId });
}
}
return View();
}
When (+) clicked
$('#allAnswers').append(
'<div class="input-group col-lg-4">' +
'<input class="form-control" name="Answers"> ' +
'<div class="input-group-btn">' +
' <button type="button" class="btn btn-default removeAnswer"><span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span></button>' +
'</div> </div>');
As discussed.. here is how i would approach this.
I have a view model to hold the questions and answers and the selected question to which we will be adding answers.
public class CurrentViewModel
{
public string QuestionSelected { get; set; }
public List<SelectListItem> Questions { get; set; }
public List<string> Answers { get; set; }
}
Then in your controller we have an action to return the view, an action to get the answers for the selected question, an action to add a new answer for the selected question and also a save method which just demonstrates the final model content posted.
public class TestController : Controller
{
public ActionResult Test()
{
var model = new CurrentViewModel()
{
Questions = new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Question 1",
Value = "Question 1"
},
new SelectListItem()
{
Text = "Question 2",
Value = "Question 2"
}
},
Answers = new List<string>()
};
return View("Test", model);
}
public PartialViewResult GetAnswers(CurrentViewModel model)
{
model.Answers = new List<string>();
//model.Answers = Get Answers from some service based on QuestionSelected?!
model.Answers.Add("Answer 1");
model.Answers.Add("Answer 2"); //Add manuall for example
return PartialView("_Answers", model);
}
public PartialViewResult AddAnswer(CurrentViewModel model)
{
model.Answers.Add("Add answer here...");
return PartialView("_Answers", model);
}
public ActionResult SaveQuestionsAndAnswers(CurrentViewModel model)
{
if (model.Questions.Count == 0)
{
}
return View("Test", model);
}
}
Then we have a main view for showing the questions dropdown and a partial view that will show us the answers.
Main View
#model TestMVC.Models.CurrentViewModel
#{
ViewBag.Title = "Test";
}
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div id="divBodyContent">
<div>
<h3>Q & A</h3>
</div>
#using (Html.BeginForm("SaveQuestionsAndAnswers", "Test", FormMethod.Post, new { id = "frmQandA" }))
{
#Html.Label("lblQ", "Questions", new { #class = "form-control inline" })
#Html.DropDownListFor(model => model.QuestionSelected, Model.Questions, "Select--", new { #class = "form-control inline", id="ddQuestions" })
<div id="divAnswers">
#Html.Partial("_Answers")
</div>
<div style="margin-top: 1%;">
<button id="btnSave" type="submit" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">save</button>
</div>
}
</div>
<script>
$("#ddQuestions").on("change", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetAnswers", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
$("#divAnswers").html(data);
}
})});
</script>
Partial View
#model TestMVC.Models.CurrentViewModel
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div>
#for (var counter = 0; counter <= (Model.Answers.Count - 1); counter++)
{
#Html.TextBoxFor(model => model.Answers[counter], new {#class = "form-control inline"})
}
<div style="margin-top: 1%;">
<button id="btnAddAnswer" type="button" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">Add</button>
</div>
</div>
<script>
$("#btnAddAnswer").on("click", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("AddAnswer", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
$("#divAnswers").html(data);
}
})});
</script>
I've tested this locally and it works. In a nutshell, when we need a new answer adding to the model, we add it in server side so we can then bind to the model in the browser. We do this via an Ajax call on the change event of the questions drop down. The partial view iterates through each answer via a counter which generates a unique id and textbox for each answer. Adding a new answer is also achieved via ajax. These can then all be posted back.
Hope that helps.

How to add items to a Dropdownlist that is in SelectList(Enumerable.Empty<SelectListItem>() format [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 7 years ago.
Improve this question
I have a dropdownlist like this
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
it was like that because of this
<script type="text/javascript">
$(document).ready(function () {
$("#ddlGrade").change(function () {
var id = $(this).val();
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var select = $("#ddlSection");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Section"
}));
$.each(marksData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
and the JSON
public JsonResult PopulateDetails(string id)
{
List<Models.Section> a = new List<Models.Section>();
Models.ModelActions Ma = new ModelActions();
a = Ma.getSection(id);
var marksData = a.Select(c => new SelectListItem()
{
Text = c.sec_name,
Value = c.sec_id.ToString(),
});
return Json(marksData, JsonRequestBehavior.AllowGet);
}
now how can i add initial values to the dropdownlist in that format on postback? i need it for my search functionality. comments are much appreciated
EDITED:
VIEW:
<legend>CreateStudent</legend>
Full Name:
#Html.TextBox("searchTerm", null, new { id = "txtSearch" })
<input type="submit" value="search" name="submitbutton" />
<div class="editor-label">
#Html.LabelFor(model => model.si_id)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.si_id, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.si_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_fname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_fname)
#Html.ValidationMessageFor(model => model.si_fname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_mname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_mname)
#Html.ValidationMessageFor(model => model.si_mname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_lname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_lname)
#Html.ValidationMessageFor(model => model.si_lname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_gl_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_gl_id, new SelectList(Model.GradeLevel,"gl_id","gl_name"),"Select Grade Level", new { id = "ddlGrade" })
#Html.ValidationMessageFor(model => model.si_gl_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_sec_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
#Html.ValidationMessageFor(model => model.si_sec_id)
</div>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
</fieldset>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
Controller
[HttpPost]
public ActionResult RegisterStudent(CreateStudent Create, string submitbutton, string searchTerm)
{
acgs_qm.Models.ModelActions Ma = new acgs_qm.Models.ModelActions();
List<CreateStudent> stud = new List<CreateStudent>();
switch (submitbutton)
{
case "search":
ModelState.Clear();
var model = new CreateStudent
{
GradeLevel = Ma.getGrade(),
//Guardian = Ma.getGuardian(),
si_id = Ma.getStringval(searchTerm,"si_id","student_info_tb","si_fullname"),
si_fname = Ma.getStringval(searchTerm, "si_fname", "student_info_tb", "si_fullname"),
si_mname = Ma.getStringval(searchTerm, "si_mname", "student_info_tb", "si_fullname"),
si_lname = Ma.getStringval(searchTerm, "si_lname", "student_info_tb", "si_fullname"),
si_gender = Ma.getStringval(searchTerm, "si_gender", "student_info_tb", "si_fullname"),
};
return View("RegisterStudent",model);
case "Create":
if (ModelState.IsValid)
{
Ma.insertStudent(Create);
}
Create.GradeLevel = Ma.getGrade();
Create.si_id = Ma.getcode("student_info_tb", "si_id", "1");
return View(Create);
default:
return View(Create);
}
}
Change your implementation as follows :
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var $select = $("#ddlSection");
$select.empty();
$select.append('<option value=' + '0' + '>' + 'Select a Section' + '</option>');
$.each(marksData, function (index, itemData) {
$select.append('<option value=' + itemData.Value + '>' + itemData.Text + '</option>');
});
});
Try this
$("#ddlSection").change(function () {
var Id = this.value;
if (Id != 0) {
$.ajax({
type: "POST",
url: "/Employee/PopulateDetails",
data: JSON.stringify({ Id: Id }),
dataType: "text",
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
$("#ddlSection").empty();
$('#ddlSection').append("<option value='0'>Select Selection...</option>");
var yourArray = $.parseJSON(data);
if (yourArray != null) {
for (var i = 0; i < yourArray.length; i++) {
$('#ddlSection').append("<option value='" + yourArray[i].YourFiledName + "'>" + yourArray[i].YourFiledName + "</option>");
}
}
},
error: function (response) {
if (response != 1) {
alert("Error!!!!");
location.reload();
}
}
});
}
else {
alert("Please Select Any Value Name....");
}
});

Html.TextBoxFor showing Empty Value but the model is not empty

Hi all I'm having trouble correctly display the data in the textbox
This is my Print partialView
#{ Layout = null; }
#model Estudio.WebUI.Models.PrintViewModel
#using (Ajax.BeginForm("Print", new { #class = "openDialog data-dialog-id='PrintDialog' data-dialog-Title='Print'" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "PrintDialog" }))
{
#Html.HiddenFor(m => m.FacturaId)
<div class="editor-label">
#Html.LabelFor(m => m.NComprobante)
<div class="editor-field">
#Html.TextBoxFor(m => m.NComprobante)
</div>
</div>
<br/>
<div class="editor-label">
#Html.LabelFor(m => m.SendMail)
<div class="editor-field">
#Html.CheckBoxFor(m => m.SendMail)
</div>
</div>
<input type="submit" name="Imprimir" value="Imprimir" id="Imprimir"/>
<script type="text/javascript">
$(document).ready(function () {
$("#NComprobante").mask("99999-999999999999");
});
</script>
}
This is ActionResult Print
public ActionResult Print(string id)
{
...
var model = new PrintViewModel
{
FacturaId = factura.FacturaId,
NComprobante = numero[0] + "-" + comprabante.ToString("000000000000")
};
return PartialView("Print", model);
}
Can anyone help?
wrong code on
NComprobante = numero[0] + "-" + comprabante.ToString("000000000000")
the correct is:
var comprabante = numero[0] + "-" + (Convert.ToDouble(numero[1]) + 1).ToString("0000000000000");

Categories