2

I have one of the tables with the attributes: id, school name, student name. I want to insert new item look like:

School Name : Elementary School (Select List)

Students Name : A, B, C, D (TextBox)

Join Date : 1/1/2020

And then table entries look like:

id  | school_name       | student_name  | join_date
----+-------------------+---------------+----------------
1   | Elementary School | A             | 1/1/2020
2   | Elementary School | B             | 1/1/2020
3   | Elementary School | C             | 1/1/2020
4   | Elementary School | D             | 1/1/2020

Model studentdb.cs

public partial class studentdb
{
        public int id { get; set; }
        public string school_name { get; set; }
        public string student_name { get; set; }
        public DateTime join_date { get; set; }
} 

CreateController.cs

[HttpPost]
public ActionResult CreateStudent(studentdb Student)
{
    string str = Student.studentdb;
    string[] splitstr = str.Split(',');

    foreach(string s in splitstr)
    {
         db.studentdb.Add(Student);
    }

    db.SaveChanges();

    return RedirectToAction("Index", "Create");
}

Create.cshtml

<form class="form-horizontal" method="post" action="CreateStudent">
            <div><a href="#" id="addNew">Add New</a></div>
            <table class="table table-striped">

                <tr>
                    <td>School Name</td>
                    <td>
                      <select class="form-control" name="school_name">
                        <option>Elemtary School</option> 
                        <option>Junior High School</option> 
                      </select>  
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><input type="text" class="form-control" name="student_name" required></td>
                </tr>
                <tr>
                    <td>Join Date</td>
                    <td>
                        <div class="input-group">
                            <div class="input-group-addon">
                                <i class="fa fa-calendar"></i>
                            </div>
                            <input type="text" class="form-control pull-right"  name="join_date" required>
                        </div>
                    </td>
                </tr>
            </table>
            <div class="box-footer">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>

What should I do for this controller? Thanks

3
  • 2
    If you are creating multiple entries, have model that includes an array of students. Don't try and force a single entity to multiple and the other way around. You also have a non-zero chance of a students name containing a comma, how will you work around this? Your view should contain a field for join date, elementary school and name for each student some of these can be pre-populated for convenience. Commented Jan 30, 2020 at 4:37
  • We need more information on this one. Can you show us your View and how you are posting to your Controller method? Commented Jan 30, 2020 at 5:57
  • @RahulSharma I edited it Commented Jan 30, 2020 at 6:16

2 Answers 2

1

Okay, as an alternative you can use AJAX to post your form values to your Controller method. You can enforce some kind of a rule on your text-box to accept a string containing , after space.

Your View would look like:

<div><a href="#" id="addNew">Add New</a></div>
  <table class="table table-striped">    
    <tr>
      <td>School Name</td>
      <td>
        <select class="form-control" name="school_name" id="ddl_school_name">
          <option>Elemtary School</option> 
          <option>Junior High School</option> 
        </select>  
      </td>
    </tr>
    <tr>
      <td>Name</td>
      <td><input type="text" class="form-control" id="s_name" name="student_name" required></td>
    </tr>
    <tr>
      <td>Join Date</td>
      <td>
        <div class="input-group">
          <div class="input-group-addon">
            <i class="fa fa-calendar"></i>
          </div>
          <input type="text" class="form-control pull-right" id="j_date" name="join_date" required>
        </div>
      </td>
    </tr>
  </table>
  <div class="box-footer">
    <button type="button" class="btn btn-primary" onclick="SaveForm()">Submit</button>
  </div>

<script>
function SaveForm() {
  var schoolname = $("#ddl_school_name").find(':selected').text();
  var studentname= $("#s_name").val();
  var joindate= $("#j_date").val();

  var json = {
          schoolname: schoolname ,
          studentname: studentname,
          joindate: joindate
         };

  if (studentname== "" || joindate== "") {
      alert("Missing fields");
      return false;
  }

  $.ajax({
      type: "post",
      dataType: "json",
      data: {"json": JSON.stringify(json)},,
      url: "@Url.Action("CreateStudent","Create")",
      success: function (result) {
          alert("Inserted student data");
      },
      error:function(result){
          alert("Could not insert student data");
      }            
  });
}
</script>

And your Controller method would look like:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult CreateStudent(string json)
{

  var serializer = new JavaScriptSerializer();
  dynamic jsondata = serializer.Deserialize(json, typeof(object));

  //Get your variables here from AJAX call
  var schoolname= jsondata["schoolname"];
  var studentname= jsondata["studentname"];
  var joindate= jsondata["joindate"];

  studentdb student=new studentdb();
  student.school_name=schoolname;
  student.join_date=Convert.ToDateTime(joindate);

  string[] splitstr = studentname.Split(',');    
  foreach(string s in splitstr)
  {
     student.student_name=s;
     db.studentdb.Add(student);
  }

  db.SaveChanges();

  return RedirectToAction("Index", "Create");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Bind model in controller this way

    [HttpPost]
    public ActionResult CreateStudent(Classroom roomVm)
    {
        string str = roomVm.student_name;
        string[] studentNames= str.Split(',');

        foreach(string s in studentNames)
        { var student = new Student();

           student.student_name  =s;
           student.school_name=roomVm.school_name;
           student.join_date=roomVm.join_date;


             db.studentDbSet.Add(student);
        }

        db.SaveChanges();

        return RedirectToAction("Index", "Create");
    }

2 Comments

Thankyou for the response. I am wrongly naming the studentdb class to be a Classroom class. The truth is the student class, I've edited it.
Looks like you're newbee in asp.net mvc, I suggest you to separate view model from db entity, and studentdb - is not very good name for entity. Name StudentViewModel- model and Student-entity class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.