logo
down
shadow

mvc ajax form post null list issue


mvc ajax form post null list issue

By : Sandy Prasetya
Date : November 22 2020, 11:05 AM
Hope this helps What i did after messing up with it that on list creating on Add Test i added a dummy empty entry on index 0 of the list and on retrieving while saving in db i am skipping the 0th index of the list, here is the code:
code :
 [HttpPost]
        public ActionResult AddTest(int TestId,long Charges, string TestName)
        {
            List<Test> bookedTests = new List<Test>();

            if (Session["BookedTests"] != null)
            {
                bookedTests = (List<Test>)Session["BookedTests"];
            }

            else
            {

                Test dummyTest = new Test();

                dummyTest.TestId = 0;
                dummyTest.Charges = 0;
                dummyTest.TestName = "dummy";

                bookedTests.Add(dummyTest);

            }

            Test objTest = new Test();

            objTest.TestId = TestId;
            objTest.Charges = Charges;
            objTest.TestName = TestName;

            bookedTests.Add(objTest);

            Session["BookedTests"] = bookedTests;

            return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
        }
[HttpPost]
        public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
        {

            using (var db = new cloud_clinicEntities())
            using (var scope = new TransactionScope())
            {
                org_requestm objRequestM = new org_requestm();

                objRequestM.authcode1 = form.AuthCode1;
                objRequestM.admission_no = form.admission_no;
                objRequestM.bed_no = form.bed_no;
                objRequestM.ward_no = form.ward_no;
                objRequestM.patient_id = form.patient_id;
                objRequestM.RequestType = form.TypeOfRequest;
                if (form.DependentId == 0)
                {
                    objRequestM.cliq_dependent_id = null;
                }
                else
                {
                    objRequestM.cliq_dependent_id = form.DependentId;
                }
                if (form.CliqDoctorID != 0)
                {
                    objRequestM.cliq_doctor_id = form.CliqDoctorID;
                }
                if (!string.IsNullOrEmpty(form.DoctorName))
                {
                    objRequestM.doctor_name = form.DoctorName;
                }

                objRequestM.request_total_amount = 0;

                for (int i = 0; i < form.BookedTests.Count; i++)
                {
                    if (form.BookedTests[i].Charges != 0)
                    {
                        objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
                    }
                }


                objRequestM.cliq_panel_id = form.CliqPanelID;

                if (Session["AccountType"].ToString() == "lab")
                {
                    objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
                }
                else
                {
                    objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
                }
                objRequestM.enteredon = DateTime.Now;

                objRequestM.org_request_type_id = form.RequestType;

                if (Request.Files != null)
                {
                    foreach (string requestFile in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[requestFile];
                        if (file.ContentLength > 0)
                        {
                            string fileName = Path.GetFileName(file.FileName);
                            string directory = Server.MapPath("~/uploads/");

                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                            string path = Path.Combine(directory, fileName);

                            file.SaveAs(path);

                            objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
                        }
                    }
                }

                db.org_requestm.Add(objRequestM);

                db.SaveChanges();


                long RequestmId = db.org_requestm.Max(o => o.id);

                for (int i = 0; i < form.BookedTests.Count; i++)
                {

                        if (form.BookedTests[i].TestId != 0)
                        {
                            org_requestd objRequestd = new org_requestd();

                            objRequestd.amount = form.BookedTests[i].Charges;
                            objRequestd.lims_test_id = form.BookedTests[i].TestId;
                            objRequestd.lims_test_name = form.BookedTests[i].TestName;
                            objRequestd.Status = "P";
                            objRequestd.requestm_id = RequestmId;


                            db.org_requestd.Add(objRequestd);

                            try
                            {
                                db.SaveChanges();
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException e)
                            {
                                var outputLines = new List<string>();
                                foreach (var eve in e.EntityValidationErrors)
                                {
                                    outputLines.Add(string.Format(
                                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                                    foreach (var ve in eve.ValidationErrors)
                                    {
                                        outputLines.Add(string.Format(
                                            "- Property: \"{0}\", Error: \"{1}\"",
                                            ve.PropertyName, ve.ErrorMessage));
                                    }
                                }
                                System.IO.File.AppendAllLines(@"d:\EFerrors.txt", outputLines);
                            }
                        }

                }


                scope.Complete();


                Session.Remove("BookedTests");

                return "success";
            }
        }


Share : facebook icon twitter icon
I have @Ajax.BeginForm in each row of Table, When I make post request using that form then Model is null except first ro

I have @Ajax.BeginForm in each row of Table, When I make post request using that form then Model is null except first ro


By : Ramesh
Date : March 29 2020, 07:55 AM
help you fix your problem I have @Ajax.BeginForm in each row of Table, When I make post request using that form then Model is null except first row. , Well I don't really understand what you'd like to do.
code :
public ActionResult _SaveGroupMatchs(TravelAdsRulesMatchsGroups mm)
@Html.HiddenFor(model => model[i].Id)
@* for your TravelAdsRulesMatchsGroups properties *@
@Html.Hidden("id", Model[i].id)
@* ... and so on ...*@


@* for the lstMatches property, which is a list of MatchModel *@
@for (var j = 0; j < Model[i].lstMatches.Count; j++)
{
    @Html.Hidden("lstMatches[" + j.ToString() + "].match_rule_id", Model[i].lstMatches[j].match_rule_id)
    @* ... and so on ...*@
}
Jquery AJAX form POST submit issue

Jquery AJAX form POST submit issue


By : SliceMusik
Date : March 29 2020, 07:55 AM
wish of those help I have the following AJAX code, on success, I would like to redirect using post method so I have a dummy form (id="form-post-change-tab") and redirecting to ./landing via post. , That is because your form id does not have quotes around it !
code :
$(#form-post-change-tab).submit()
$('#form-post-change-tab').submit() 
html.beginForm post null value for List<strongly typed> to controller via jQuery Ajax function in ASP>NET-MVC5

html.beginForm post null value for List<strongly typed> to controller via jQuery Ajax function in ASP>NET-MVC5


By : harsh pathak
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You are using same controller post action for different forms. Your action update model (list of entities) only entity present on first position. Your models has a list of [entity0, entity1] but in form view you remove entity0 because you are binding only one entity1 from model having list.
Here you have 2 approaches:
code :
    public ActionResult EditEmergencyContact (List<EmergencyContact> _emergencyContactModel)
            {

                try
                {

                    if (_emergencyContactModel != null && _emergencyContactModel.Count() > 0)

                    {
                        if (ModelState.IsValid)
                        {
                            bool validation = true;

                            for (int i = 1; i < _emergencyContactModel.Count(); i++)
                            {

                                if (_emergencyContactModel[i].EmergencyContactID != null)
                                {

                                    int _entityID = _studentProfileServices.EditEmergencyContactByStudentID(

                                    new EmergencyContact
                                    {
                                        EmergencyContactID = _emergencyContactModel[i].EmergencyContactID,
                                        StudentID = _emergencyContactModel[i].StudentID,
                                        NameOfContact = _emergencyContactModel[i].NameOfContact,
                                        Relationship = _emergencyContactModel[i].Relationship,
                                        Telephone = _emergencyContactModel[i].Telephone,
                                        Mobile = _emergencyContactModel[i].Mobile,
                                        Address = _emergencyContactModel[i].Address
                                    });

                                    if (_entityID == 0)
                                    {
                                        validation = false;
                                        break;
                                    }
                                }
                            }

                            if (validation)
                            {
                                return Json(new { Response = "Success" });
                            }
                            else
                            {
                                return Json(new { Response = "Error" });
                            }
                        }
                        else
                        {
                            return Json(new { Response = "Invalid Entry" });
                        }
                    }
                    else
                    {
                        return Json(new { Response = "Error! In Updating Record" });
                    }
                }
                catch (DataException ex)
                {
                    ModelState.AddModelError("", "Unable To Edit Emergency Contact" + ex);
                }

                return RedirectToAction("MyProfile", "StudentProfile");
            }
@using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo2EmergencyContactForm" }))
{
  @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Emergency Contact 2</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @* here you pas List 0  model recieved value and viceversa if you edit model[0]*@
    @Html.HiddenFor(model => model[0].EmergencyContactID)
    @Html.HiddenFor(model => model[0].StudentID)
    @Html.HiddenFor(model => model[0].NameOfContact)
    @Html.HiddenFor(model => model[0].Relationship)
    @Html.HiddenFor(model => model[0].Telephone)
    @Html.HiddenFor(model => model[0].Mobile)
    @Html.HiddenFor(model => model[0].Address)
    @Html.HiddenFor(model => model[0].Address)

    @Html.HiddenFor(model => model[1].EmergencyContactID)

    <div class="form-group">
        @Html.LabelFor(model => model[1].StudentID, "StudentID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].StudentID, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].StudentID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model[1].NameOfContact, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].NameOfContact, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].NameOfContact, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model[1].Relationship, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].Relationship, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].Relationship, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model[1].Telephone, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].Telephone, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].Telephone, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model[1].Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].Mobile, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].Mobile, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model[1].Address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model[1].Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model[1].Address, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
 </div>
}
int _entityID_0 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
    EmergencyContactID = _emergencyContactModel[0].EmergencyContactID,
    StudentID = _emergencyContactModel[0].StudentID,
    NameOfContact = _emergencyContactModel[0].NameOfContact,
    Relationship = _emergencyContactModel[0].Relationship,
    Telephone = _emergencyContactModel[0].Telephone,
    Mobile = _emergencyContactModel[0].Mobile,
    Address = _emergencyContactModel[0].Address
});

int _entityID_1 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
    EmergencyContactID = _emergencyContactModel[1].EmergencyContactID,
    StudentID = _emergencyContactModel[1].StudentID,
    NameOfContact = _emergencyContactModel[1].NameOfContact,
    Relationship = _emergencyContactModel[1].Relationship,
    Telephone = _emergencyContactModel[1].Telephone,
    Mobile = _emergencyContactModel[1].Mobile,
    Address = _emergencyContactModel[1].Address
});

if (_entityID_0 != 0 && _entityID_1 != 0)
{
    return Json(new { Response = "Success" });
}
else
{
    return Json(new { Response = "Error" });
}
Ajax post to MVC controller List<T> properties correct count but null

Ajax post to MVC controller List<T> properties correct count but null


By : Gaganpreet Singh
Date : March 29 2020, 07:55 AM
I wish this helpful for you You cannot bind a
Ajax form post issue

Ajax form post issue


By : Javier Vasquez
Date : March 29 2020, 07:55 AM
seems to work fine It looks like you are not including the data with your post request.
Include the "data" attribute in the object you pass to .ajax:
code :
$.ajax({
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    headers: { "Upgrade-Insecure-Requests": "1",
                Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    },
    crossDomain: true,
    url: $(this).attr('action'),
    data: someData, # <----------HERE
    beforeSend: function(){
        form.prepend(form_status.html('Email is sending...'));
    }
})
let someData = $('#main-contact-form').serialize();
Related Posts Related Posts :
  • X509Certificate2.Import with NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG
  • Model expands on moving horizontally in unity
  • Custom response when Model binding fails ASP.NET Core API
  • Can you Serialize inside a set of Attributes by Set of Attributes?
  • ASP.NET Web API 2 - Filter POST requests by Query String
  • ValidationAttribute injecting services for unobtrusive client validation
  • UWP - Middle Mouse Wheel Button Click Event Handler
  • .Net Core 2.2 Cookie Authentication Problem
  • How have more than two expands in restier asp.net
  • Autofac Resolve with TypedParameter always pick up first the same type parameter expected?
  • Regluar expression problem. It does not find the needed part of the string
  • How to make a Sum of values in a list for Charts? [ SOLVED ]
  • Nested HttpWebRequest in c#
  • How to read a struct containing array of structs from TwinCat to C#
  • HttpPostedFileBase gets content length to 0 when C# iterates the zipfile
  • xamarin forms HttpClient incomplete Json
  • How can i write more than one string in one line?
  • ASP.NET Core MVC equivalent of Start Action Specific Page
  • Dynamic grid row count and column count with XAML
  • How to query the first entry in each group in NHibernate
  • How can you migrate an entity framework project to .NET standard when the fluent configuration is using HasDatabaseGener
  • Program freezes when using RSA.ImportParameters() on android platform
  • SQL select query - no seconds or milliseconds in datetime
  • ASP.NET Core CORS combining policies; enablecors in controller vs midleware configuration
  • How to stop Firebase Realtime Database Unity SDK listener load all child data at start of application
  • How to offset the Y position of every second column in a Grid Control
  • Client side or server side error on SecurityTokenValidationException certificate expiration
  • if String is empty then data is not inserting
  • How to pass dynamic parameter and inject repository in ActionFilter in asp.net Core 2.2?
  • Select element where attribute contains a certain substring
  • How to get JSON response for column names in database table
  • How can I safely unsubscribe from an Action in one line?
  • How to change icon ( of main Form + another child forms) programatically in c# code while compilation
  • Why is the result of adding two null strings not null?
  • Getting deserialized values
  • What are difference between use invoke and synchronizationcontext.Post object?
  • Asynchronous Communication
  • No connectionString could be found in the test project application config file
  • Building a website that converts address to longitude and latitude and saves in the database
  • WPF Border shape
  • How to Add ItemArray to DataRow at a specific Location in DataTable
  • Try within Linq query
  • How to reduce the execution time?
  • What does T stands for in C#?
  • WPF MVVM Databinding with parameters?
  • How to apply a custom style to a control inside of a custom control template?
  • ASP.NET 4.5 data binding model SelectMethod throw error
  • How does the compiler recognise Nullable<T> to be a 'special type'?
  • Populate DataGridview upon ComboBox selection
  • KeyCommand disabled MenuItem
  • get the data that was returned from the stored procedure SQL Server 2008 silvelight C# Linq
  • Text boxes are not filling when the Form Loads, Windows Form Application
  • multiple input and multiple output in ssis with executing bat file
  • How to replace a string using the original matched value
  • Splitting Date from DateTime
  • How to manage multiple windows in MVVM
  • Setting active a Chrome window (C++)
  • Adding a Custom Task Pane to Word (Without using VSTO)
  • Session is set or not in ASP.NET
  • Not able to pass eval to javascript function
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org