I get a null variable in my asp.net mvc project - asp.net

This is Ajax code
<script>
$(document).ready(function () {
$("#btnKaydet").click(function () {
debugger
var data = $("#myForm").serialize();
$.ajax({
type:"POST",
url: "/Home/Olusturma",
data: data,
success: function (response) {
alert("Kayıt İşlemi Başarılı")
}
})
})
})
</script>
This is saving button code
<form id="myForm">
<input type="button" value="Buradan Kaydet" class=" btn btn-default" id="btnKaydet" />
</form>
This is HomeController code
public ActionResult Olusturma()
{
KullaniciDBEntities db = new KullaniciDBEntities();
List<Kisi> kL = db.Kisi.ToList();
ViewBag.kisiList = new SelectList(kL, "AdSoyad", "Email", "Yas", "Konum", "Telefon", "Parola");
return View();
}
[HttpPost]
public ActionResult Olusturma(KullaniciDBEntities model)
{
try
{
KullaniciDBEntities db = new KullaniciDBEntities();
List<Kisi> kL = db.Kisi.ToList();
ViewBag.kisiList = new SelectList(kL, "AdSoyad", "Email", "Yas", "Konum", "Telefon", "Parola");
Kisi k = new Kisi();
k.ID = model.ID;
k.AdSoyad = model.AdSoyad;
k.Email = model.Email;
k.Yas = model.Yas;
k.Konum = model.Konum;
k.Telefon = model.Telefon;
k.Parola = model.Parola;
db.Kisi.Add(k);
db.SaveChanges();
int SonId = k.ID;
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("Listeleme");
}
Hello everyone. When ı run my project, ı get a error. My variables seems normal but they dont show anything.It shows (null) variable in their places .How can ı fix this error? I have controller, KullaniciDBentities model and View parts.

Related

How to get the dynamic button's id ASP.Net Core

I am trying to find a way to send the id of the clicked button to the backend. The problem is that I am creating lots of buttons with one method but the id is different.
#foreach (var item in Model.showManager.GetMovies())
{
i++;
#if (Model.user.IsAdmin == true)
{
<input class="btn_confirm" type="submit" id=i value="Delete"/>
}
}
The point is that every button is created with different id and I want to send that id to the backend.
Update
My demo is a MVC project, I have a DynamicButtonController and a Index view:
DynamicButtonController:
public class DynamicButtonController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(int id)
{
return View();
}
}
Index view :
#for (var i = 0; i < 5;i++ )
{
<input class="btn_confirm" type="submit" id=#i value="Delete" />
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(".btn_confirm").click(function()
{
var data = (this).id;
$.ajax({
type: "POST",
url: '/DynamicButton/Index/',
data: { id: data }
});
});
</script>
result:
If you use Razor pages, you can refer to the below demo,use asp-route-id="#i"
ButtonIdModel:
public class ButtonIdModel : PageModel
{
public void OnGet()
{
}
public void OnPost(string id)
{
}
}
ButtonId.cshtml:
#page
#model yourproject.Pages.ButtonIdModel
<form method="post">
#for (var i = 0; i < 5;i++ )
{
<input class="btn_confirm" type="submit" id=#i value="Delete" asp-route-id="#i" />
}
</form>
The point is that every button is created with different id and I want
to send that id to the backend.
Well, based on your issue, you want to bind all the button ids then want to pass those Ids in your backend.
However, another answer has guided you how to pass id to your controller. Nonetheless, it doesn't resolve your main concern that is how to pass the list of ids on button submit.
Algorithm:
As said earlier, first you have to get the list of button ids which has been generated from your foreach loop and you have to push them in an array, finally need to pass those in your controller (backend). Here, importantly you have to keep in mind, it doesn't matter how the button been generated, for loop or foreach loop the fact is your button should have class name of same type and the ids for instance: class="myBtnClass btn btn-danger" and id="btnId:#i"
Solution:
View:
#{
ViewData["Title"] = "ViewGetDynamicButtonsID";
}
<div>
#for (var i = 1; i < 5; i++)
{
<input class="myBtnClass btn btn-danger" id="btnId:#i" value="Delete:#i" style="margin-bottom:2px" /> <br />
}
<input type="submit" id="btnSubmit" class="btn btn-success" value="Submit" />
</div>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSubmit").on("click", function () {
var ids = [];
$(".myBtnClass").each(function () {
//Getting All Button Ids and Pusing in array
ids.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: 'http://localhost:5094/stuff/GetAllButtonId',
datatype: "json",
data: { buttonids: ids },
success: function (res) {
console.log(res);
alert("It works")
},
error: function () {
alert("It failed");
}
});
return false;
});
});
</script>
}
Controller:
public IActionResult CreateDynamicButton()// This is for loading the view
{
return View();
}
[HttpPost]
public IActionResult GetAllButtonId(List<string> buttonids) // This for submit the button request.
{
return Ok(buttonids);
}
Note: I have defined Button Ids as List<string> thus you can do it as your convenient type
Output:

my action method returning {"success=true,message="work done"} ASP.net MVC 5

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:
In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

Asp net core mvc model details not validating and passing values to controller

In the Edit method of a controller, I cannot successfully validate and pass the details of a model. But when I add new row, it validates and pass it's values to the controller.
Here is the sample output:
The two records is not passing and validating but when I add a new row, the record from new row validates and passes
Here is my code for getting the existing details
var form = $('form');
$.ajax({
url: '/Journals/EditJournalDetails',
data: {
id: #Model.Id
},
success: function (data) {
$('#journalRow').append('<tr>' + data + '</tr>');
$('tbody#journalRow>tr.checkDetails').appendTo('#checkRow');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
}
});
the code for EditJournalDetails
#model IEnumerable<SimplyAccounting.Models.TransactionViewModels.JournalDetailsViewModel>
#using (Html.BeginCollectionItem("JournalDetailsViewModel"))
{
#foreach (var item in Model)
{
//row values here
}
}
Controller code:
public async Task<IActionResult> EditJournalDetails(int? id)
{
var journaldetails = await _context.JournalDetails.Where(m => m.JournalId == id).ToListAsync();
var jdvmodel = _mapper.Map<List<JournalDetailsViewModel>>(journaldetails);
foreach(var item in jdvmodel)
{
//retrieve data here
}
return PartialView("_EditJournalDetails", jdvmodel);
}
Add row code JS:
function GetRow() {
var form = $('form');
$.ajax({
url: '/Journals/CreateJournalDetails',
success: function (data) {
$('#journalRow').append('<tr>' + data + '</tr>');
$('tbody#journalRow>tr.checkDetails').appendTo('#checkRow');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
}
});
}
CreateJournalDetails partialview code:
#model SimplyAccounting.Models.TransactionViewModels.JournalDetailsViewModel
#using (Html.BeginCollectionItem("JournalDetailsViewModel"))
{
//row codes here
}
Controller code:
public IActionResult CreateJournalDetails(JournalDetailsViewModel vmodel)
{
vmodel = new JournalDetailsViewModel();
//some code here
return PartialView("_CreateJournalDetails", vmodel);
}
Solve the issues using this code
View
<tbody id="journalRow">
#foreach(var item in Model.JournalDetailsViewModel)
{
#Html.Partial("_JournalDetails", item)
}
</tbody>
PartialView
#model SimplyAccounting.Models.TransactionViewModels.JournalDetailsViewModel
#using (Html.BeginCollectionItem("JournalDetailsViewModel"))
{
<tr class="checkDetails" id="#Model.Guid">
<td>
}
}

Testing Model is valid

Working on a web app, MVC 5 in VS 2015.
Here is my model:
public class InfoFormulaireEmployeModele
{
[Required(ErrorMessage =" *You must provide a date")]
[RegularExpression("^[0-9]{8}$", ErrorMessage ="The date must be of the format AAAAMMJJ")]
public string dateEvenementInitial { get; set; }
}
When I try to enter some invalid input, let's say '12ab' , it works fine, I'm back on the page with the error message.
Here is my view:
#using PortailLibreService.Models
#model InfoFormulaireEmployeModele
#{
ViewBag.Title = "ChampsFormulaireInvalidite";
}
#using (Html.BeginForm())
{
<div class="editor-field">
<b>Initial event </b><br>
<p>When did the initial event occured?</p>
#Html.TextBoxFor(x => x.dateEvenementInitial, new { #placeholder = "AAAAMMJJ" }) #Html.ValidationMessageFor(x => x.dateEvenementInitial, null, new { #class = "error" })
</div>
<input type="submit" name="Save" value="Submit" />
}
I wanted to create a unit test to be sure that my model wouldn't be valid with an invalid date entry.
Here is my unit test:
[TestMethod]
public void testRetourPossibleInvalide()
{
InfoFormulaireEmployeModele modelDuplicat = new InfoFormulaireEmployeModele();
modelDuplicat.dateEvenementInitial = "abc";
InvFormController controlleur = lib.getController("100237");
var result = controlleur.ChampsFormulaireInvalidite(modelDuplicat);
Assert.AreEqual(false, controlleur.ModelState.IsValid);
}
For some reason the test fails, controlleur.ModelState.IsValid is true while it should be false. If I test it with only numerical values it's fine. For example, this test passed:
[TestMethod]
public void testRetourPossibleInvalide()
{
InfoFormulaireEmployeModele modelDuplicat = new InfoFormulaireEmployeModele();
modelDuplicat.dateRetourPossible = "129";
InvFormController controlleur = lib.getController("100237");
var result = controlleur.ChampsFormulaireInvalidite(modelDuplicat);
Assert.AreEqual(false, controlleur.ModelState.IsValid);
}
controlleur.ModelState.IsValid is false while running the test, so the test passes.
I tried to put a breakpoint inside my controller method but I can't reach it while debugging..
You would have to act as the framework, which usually does all the checking for you.
[TestMethod]
public void testRetourPossibleInvalide() {
var model = new InfoFormulaireEmployeModele();
model.dateEvenementInitial = "abc";
var controller = new InvFormController();
var bindingContext = new ModelBindingContext() {
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
};
var boundModel = new DefaultModelBinder().BindModel(new ControllerContext(), bindingContext);
controller.ModelState.Clear();
controller.ModelState.Merge(bindingContext.ModelState);
var result = controller.ChampsFormulaireInvalidite(model);
Assert.AreEqual(false, controller.ModelState.IsValid);
}

BeginCollectionItem() gives only lastly appended item for PostBack

InquiryOrderViewModel
public class InquiryOrderViewModel
{
public InquiryOrder InquiryOrder { get; set; }
public List<InquiryOrderDetail> InquiryOrderDetails { get; set; }
}
InquiryOrderIndex View and the Script to add items
#model eKnittingData.InquiryOrderViewModel
#using (Html.BeginForm("Save", "InquiryOrder"))
{
<div id="editorRows">
#foreach (var item in Model.InquiryOrderDetails)
{
Html.RenderPartial("_DetailEditorRow", item);
}
</div>
#Html.ActionLink("Add another...", null, null, new { id = "addItem" })
<div class="col-md-6"> <input type="submit" value="Save" class="btn btn-success" /> </div>
}
<script>
$('#addItem').click(function (e) {
e.preventDefault();
var isExist = false;
$('.editorRow').each(function () {
if ($(this).children('.class01').val() == 0 || $(this).children('.class02').find("option:selected").text() == "Select") {
isExist = true;
return false;
}
});
if (isExist == false) {
$('.editorRow').each(function () {
$(".editorRow").children().attr("disabled", "disabled");
});
$.ajax({
url: '#Url.Action("BlankEditorRow", "InquiryOrder")',
cache: false,
success: function (data) {
$("#editorRows").append(data);
}
});
}
});
</script>
DetailEditorRow PartialView
#model eKnittingData.InquiryOrderDetail
#using eKnitting.Helpers
#using (Html.BeginCollectionItem("InquiryOrderDetails"))
{
<div class="editorRow">
#Html.DropDownListFor(a => a.ComponentId, (SelectList)ViewBag.CompList, "Select", new { Class = "class02" })
#Html.DropDownListFor(a => a.DesignCodeId, (SelectList)ViewBag.DCodeList, "Select", new { Class = "class03" })
#Html.TextBoxFor(a => a.NoOfParts, new { Class = "class01" })
delete
</div>
}
ActionResult which returns PartialView
public ActionResult BlankEditorRow()
{
var objContext = new KnittingdbContext();
ViewBag.CompList = new SelectList(objContext.Components, "ComponentId", "ComponentName");
ViewBag.DCodeList = new SelectList(objContext.DesignCodes, "DesignCodeId", "DesignCodeCode");
return PartialView("_DetailEditorRow", new InquiryOrderDetail());
}
ActionResult for 'GET'
var objContext = new KnittingdbContext();
var newIovm = new InquiryOrderViewModel();
var newIo = new InquiryOrder();
//initial item
var newIoD = new List<InquiryOrderDetail>
{
new InquiryOrderDetail()
};
newIovm.InquiryOrder = newIo;
newIovm.InquiryOrderDetails = newIoD;
ViewBag.CompList = new SelectList(objContext.Components, "ComponentId", "ComponentName");
ViewBag.DCodeList = new SelectList(objContext.DesignCodes, "DesignCodeId", "DesignCodeCode");
return View(newIovm);
ActionResult for 'POST'
public ActionResult Save(InquiryOrderViewModel inquiryOrderViewModel)
{
.................
}
When i click the add button im able to add items dynamically. But for PostBack it gives me only the lastly appended item. I checked it by putting a break point on post ActionResult. How can i get the whole collection for PostBack? Where did i go wrong? All help appreciated. Thanks!
Your scripts sets a variable var isExist = false;. When you add a new item, you check if the value is false (which it is if you got that far) and then disable all existing inputs.
Disabled form controls do not post back, hence you only get the values for the last row you have added.
Its unclear why you would want to disable them, but if you want to prevent editing of existing rows, the make them readonly
$(".editorRow").children().prop("readonly", true);

Resources