I have a table in view which is static in nature.I am trying to post data to Controller without using Jquery Ajax. Is it possible?How can I retrieve all these data in Action "bulk_insert". I am able to send this bulk data to controller using jquery ajax but I am unable to send it directly.
My view :
#using entity_framework.Models
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h1>Static data</h1>
<div>
#using (Html.BeginForm("bulk_insert", "Form", FormMethod.Post, new { enctype = "multipart/form-data", id = "postForm" }))
{
<table id="myTable" class="table table-striped">
<thead>
<tr>
<td>Menu Item Id</td>
<td>Menu Item Name</td>
<td>Menu Qty</td>
<td>Menu Rate</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="hidden" name="menu_item_id[0]" value="1" /><span>1</span></td>
<td><input type="hidden" name="menu_item_name[0]" value="chaumin" /><span>chaumin</span></td>
<td><input type="hidden" name="data[0].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[0].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[0].total" value="200"><span>200</span></td>
</tr>
<tr>
<td><input type="hidden" name="data[1].menu_item_id" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].menu_item_name" value="Mo:Mo" /><span>Mo:Mo</span></td>
<td><input type="hidden" name="data[1].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[1].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].total" value="200"><span>200</span></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" />
}
</div>
I am just testing with static data right now,but I need to do it with dynamic data i.e, When a user clicks a button, a row gets added using javascript .So,I didn't use Htmlhelper. My model:
public class tabledata
{
public int menu_item_id { get; set; }
public string menu_item_name { get; set; }
public string rate { get; set; }
public string qty { get; set; }
public string total { get; set; }
}
I don't know how can I get table datas from form but my Controller method:
[HttpPost]
public ActionResult bulk_insert(IEnumerable<tabledata> data)
{
//How can I get table datas here
}
Related
View
#if (weekMaster != null)
{
using (Html.BeginForm("UpdatePlan", "generalPlan", FormMethod.Post, new { }))
{
<table class="table-bordered">
<tr>
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid" value="#obj" />
<input type="hidden" name="startDate" value="#obj.termStartDate" />
<input type="hidden" name="endDate" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession" />
</td>
}
<td>
<input type="submit" value="Update" class="btn-primary" />
</td>
</tr>
</table>
} }
Controller
[HttpPost]
public ActionResult UpdatePlan(List<DateTime> startDate, List<DateTime> endDate, List<int> weekSession, List<TermMaster> ObjHid)
{
return View();
}
I am trying pass Class Object from View to Controller above TermMaster class Object pass using input method <input type="hidden" name="ObjHid" value="#obj" /> but showing NULL value if pass single value like startDate and endDate then it work fine.
What is wrong in my code? how to pass class object List in Post Method?
Please refer Image
You can not bind objects to controller from your input. You can serialize object to json. In the controller you can take your inputs value as string and deserialize it.
You have to do it by below approach.
Create a model instead of multiple parameters, and use index in cshtml.
public class model
{
public List<DateTime> startDate { get; set; }
public List<DateTime> endDate { get; set; }
public List<int> weekSession { get; set; }
public List<TermMaster> ObjHid { get; set; }
}
CSHTML
#{ int i = 0; }
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="startDate[#i]" value="#obj.termStartDate" />
<input type="hidden" name="endDate[#i]" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession[#i]" />
</td>
i++
}
I have a form with a product-warranty list.
Each list item has checkbox.
How can I post a list of SelectecSources (warranties) to the server?
What do I have to change in that code?
The WarrantyPlusViewModel object is posted to the server. It contains a list SelectedSources which should contain the selected warranty articles.
Is it possible at all to use a complex object for the selected list?
Consider I have to post the WarrantyPlusViewModel to the server which includes
the SelectedSources property with the selected warranty objects.
#model WarrantyPlusViewModel
<div class="row">
<div class="col-md-10 col-md-offset-1">
#using (...)
{
<table class="table table-striped">
<tr>
<th></th>
<th>#Html.DisplayFor(m => m.ProductSelected.Name)</th>
<th>#Html.DisplayFor(m => m.ProductSelected.Description,l)</th>
<th>#Html.DisplayFor(m => m.ProductSelected.Price)</th>
</tr>
#foreach (var product in Model.ProductList)
{
<tr>
<td><input type="checkbox" name="SelectedSources" value="#product" /></td>
<td>#product.Name</td>
<td>#product.Description</td>
<td>#product.Price</td>
</tr>
}
</table>
<input type="submit" value="Save" />
#Html.HiddenFor(p => p.SerialNumber)
}
</div>
[HttpPost]
public virtual async Task<ActionResult> Save(WarrantyPlusViewModel viewModel)
{
return View(MVC.WarrantyPlus.WarrantyPlus.Views.OverviewWarrentyPlus, viewModel);
}
public class WarrantyPlusViewModel
{
// other properties
public List<WarrantyPlusProductViewModel> ProductList { get; set; }
public IEnumerable<WarrantyPlusProductViewModel> SelectedSources { get; set; }
}
It's really hard to bind this way. If you want to do it you should override Model Binder.
If i were on your place i will just use ProductId with some knowlege of list binding and come up with this solution:
#for (var i = 0; i < Model.ProductList.Count(); i++)
{
<tr>
<td><input type="checkbox" name="ProductList[" #i "].Id" value="#Model.ProductList[i].Id" /></td>
<td>#Model.ProductList[i].Name</td>
<td>#Model.ProductList[i].Description</td>
<td>#Model.ProductList[i].Price</td>
</tr>
}
I'm a newbie developer trying to develope a web application with asp .net mvc 5 for personel usage. The website kind of a quiz maker that I can insert Russian words with meanings and prepare a quiz by using these words.
When I trying to code the quiz page and post the data the the action method I faced some problem that I couldn't get around. I iterated through the Model, read the data and wrote them to the page. Now, what I want to do is, when I post the form, I want to get each question string and selected answer (maybe in this format: imgur.com/QETnafx). Therefore, I can easily check the answer string whether it is true or not.
I checked the following tutorials out:
Model Binding To A List by Phil Haack and ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries by Scott Hanselman
I hope I explained the situation clearly. If you need more information I can happily provide.
ViewModel
public class QuizInitializationModel
{
public List<Question> Questions { get; set; }
}
public class QuestionString
{
public int Id { get; set; }
public string WordString { get; set; }
}
public class Question
{
public QuestionString QuestionString { get; set; }
public List<AnswerItem> Answers { get; set; }
}
public class AnswerItem
{
public int Id { get; set; }
public string WordString { get; set; }
}
VIEW
#using (Html.BeginForm("Begin", "Quiz", FormMethod.Post))
{
<table class="table table-striped table-condensed table-bordered">
#for (int i = 0; i < Model.Questions.Count; i++)
{
<tr>
<td>
#Html.Label(Model.Questions[i].QuestionString.WordString)
</td>
<td>
#for (int item = 0; item < Model.Questions[0].Answers.Count; item++)
{
#Html.Label(Model.Questions[i].Answers[item].WordString)#:
#Html.RadioButton("array" + "[" + #i + "]" + "." + Model.Questions[i].QuestionString.WordString, Model.Questions[i].Answers[item].Id)<br />
}
</td>
</tr>
}
</table>
<input type="submit" value="Send" class="btn btn-primary" />
}
OUTPUT
<form action="/Admin/Quiz/Begin" method="post">
<table class="table table-striped table-condensed table-bordered">
<tr>
<td>
<label for="">вулкан</label>
</td>
<td>
<label for="trade">trade</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="18" /><br />
<label for="volcano">volcano</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="24" /><br />
<label for="talk__conversation">talk, conversation</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="15" /><br />
<label for="time">time</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="13" /><br />
<label for="income">income</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="21" /><br />
</td>
</tr>
<tr>
<td>
<label for="">мама</label>
</td>
<td>
<label for="universe">universe</label>
<input id="array_1______" name="array[1].мама" type="radio" value="25" /><br />
<label for="peace">peace</label>
<input id="array_1______" name="array[1].мама" type="radio" value="2" /><br />
<label for="value">value</label>
<input id="array_1______" name="array[1].мама" type="radio" value="20" /><br />
<label for="mom__mama">mom, mama</label>
<input id="array_1______" name="array[1].мама" type="radio" value="17" /><br />
<label for="industry">industry</label>
<input id="array_1______" name="array[1].мама" type="radio" value="19" /><br />
</td>
</tr>
</table>
And how can i fix the ids of the labels like "array_1______" ?
They appeared when I added this code "array" + "[" + #i + "]" + "." to the RadioButton control for the purpose of assign an index for each answer.
Html helpers replace invalid characters with an underscore (a period is actually not invalid, but would cause problems with jquery so its also replaced an underscore). However id attribute is not the problem, although you are generating duplicates which is invalid html.
Your manually generating the name attribute for the radio buttons which have no relationship to any property in your model so wont be bound when you post back. Your model needs to include a property you can bind the selected answer to. Modify the Question model to
public class Question
{
public QuestionString QuestionString { get; set; }
public List<AnswerItem> Answers { get; set; }
public int SelectedAnswer { get; set; } // add this
}
and modify the view to
#using (Html.BeginForm()) // note parameter not necessary if your posting to the same controller/action
{
#for (int i = 0; i < Model.Questions.Count; i++)
{
...
#Html.HiddenFor(m => m.Questions[i].QuestionString.Id)
<h2>#Model.Questions[i].QuestionString.WordString)</h2>
...
#foreach(var answer in Model.Questions[i].Answers)
{
var id = string.Format("{0}-{1}", #i, answer.Id);
#Html.Label(id, answer.WordString)
#Html.RadioButtonFor(m => m.Questions[i].SelectedAnswer, answer.ID, new { id = id })
}
....
}
<input type="submit" value="Send" class="btn btn-primary" />
}
The radio buttons are now bound to the SelectedAnswer property and when you post back, the value will be the ID of the selected AnswerItem
Note also:
A hidden input has been added for the ID of the question so the
question can be identified on post back
The question text is in a heading tag (could be another tag), but a
label is not appropriate - a label is an element associated with a
control (for setting focus to the control) but you don't have an
associated control
A unique id is created in the foreach loop so you can give each
radio button a unique id (so the html is valid) and associate the
label (the answer text) with the button
This is my code,i have also tried strongly typed view but i it does not create an upload field
#Model
namespace master_layout.Models
{
[Table("Candidates")]
public class Candidate
{
[Key]
public int CandidateID { get; set; }
public string FirstName { get; set; }
public string LastName{get;set;}
public DateTime Date{get;set;}
public string EmailID{get;set;}
public long ContactNumber{get;set;}
public long AlternateContactNumber{get;set;}
public int RecruitmentStatusID{get;set;}
public DateTime CreatedOn{get;set;}
public DateTime LastUpdatedOn{get;set;}
public byte[] Resume { get; set; }
}
public class CandidateContext : DbContext
{
public DbSet<Candidate> Candidates { get; set; }
}
The following is my controller code
Controller:
namespace proedit1.Controllers
{
public class HomeController : Controller
{
CandidateContext db = new CandidateContext();
public ActionResult Index()
{
return View(db.Candidates.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Candidate candidate)
{
if (ModelState.IsValid)
{
db.Candidates.Add(candidate);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(candidate);
}
}
}
View:
#using (Html.BeginForm("Newcandidate", "CandidatesController", FormMethod.Post, new { EncType="multipart/form-data"}))
{
<table class="navbar-form">
<tr>
<th>First Name<input type="text" placeholder="Your First Name" class="margin"/></th>
</tr>
<tr>
<th>Last Name<input type="text" placeholder="Your Last Name"/></th>
</tr>
<tr>
<th>Date of Birth <input type="date" name="db" /></th>
</tr>
<tr>
<th>E-Mail ID<input type="email" placeholder="abc#yourserviceprovider.com" /></th>
</tr>
<tr>
<th>Contact No<input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<tr>
<th>Alternate No <input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<th>Created On <input type="date" /></th>
<tr>
<th>Updated On <input type="date" /></th>
</tr>
<tr>
<th> <input type="file" placeholder="your resume in ms.word format" accept="application/msword" name="NamebtnUpload"/>
</th></tr>
</table>
<div class="row">
<div class="span4">
<input type="submit" class="btn-success" value="UPLOAD" name="Submit"/>
<input type="reset" class="btn-warning" name="Reset" />
</div>
</div>
}
I am a newbie in MVC pls provide me with the correct code to upload details to my database
There is a solution which are you looking for:
MVC 4 Razor File Upload
Create new view model for your 'view'. Don't use entity model, please.
So I have this form on my Index.cshtml view (Some data removed to shorten length),
I want to be able to submit it to the action "/Estimate/Index" defined as,
public ActionResult CreateEstimate(Estimate Est);
It creates the object just fine by serializing the data and submitting, my problem is that sub-object data is not inserted (and I understand that it doesn't cause it doesn't know how), I was curious if there was a way to tell it how to correctly create the objects in a simple/automated manner.
I've tried giving the NetUplift a different name,
Ex. name="NetUplift.Value" but this results in an internal server error (code 500).
Form in razor view - Index.cshtml
<form id="form-create-estimate">
<table id="table-create-estimate" class="table">
<tbody>
<tr>
<td class="td-header">ID</td>
<td id="td-id"><input name="ID" type="text" value="" /></td>
</tr>
<tr>
<td class="td-header">Name</td>
<td id="td-name"><input name="Name" type="text" value="" /></td>
</tr>
<tr>
<td class="td-header">Job Difficulty</td>
<td id="td-jobdifficulty"><input name="JobDifficulty" type="text" value="" /></td>
</tr>
<tr>
<td class="td-header">Type</td>
<td id="td-type"><input name="Type" type="text" value="" /></td>
</tr>
<tr>
<td class="td-header Unit">Net Uplift</td>
<td id="td-netuplift">
<input name="NetUplift" class="Unit" title="in PSF" type="number" value="" />
#*<input name="NetUplift.DataType" type="hidden" value="System.Int32" />
<input name="NetUplift.UnitOfMeasure" type="hidden" value="psf" />*#
</td>
</tr>
<tr>
<td class="td-header Unit">Joist Spacing</td>
<td id="td-joistspacing"><input name="JoistSpacing" class="FeetInch" title="in Feet' Inch''" type="text" value="" /></td>
</tr>
</tr>
<tr>
<td class="td-header">Drawing Location</td>
<td id="td-drawinglocation"><input name="DrawingLocation" type="text" value="" /></td>
</tr>
<tr>
<td><input id="button-submit-estimate" type="button" value="Create" /></td>
<td><input id="button-cancel-estimate" type="button" value="Cancel" /></td>
</tr>
</tbody>
</table>
</form>
Ajax Submit Script
// Do an Ajax Post to Submit the newly created Estimate.
function CreateEstimate() {
// Serialize the Form.
var Estimate = $("#form-create-estimate").serialize();
// Send the Serialized Form to the Server to be processed and returned
// as an updated page to asynchronously update this page.
// I guess instead of returning this entire page we could make the action
// return just a table row with the Estimate's Data, then append it to the table
// of estimates. It'll be saved to the list of estimates too so there won't be
// a chance to the lists on the Client and list on the server to be different.
$.ajax({
url: "/Estimate/CreateEstimate/",
datatype: "json",
data: Estimate,
contenttype: "application/json",
success: function (Data, Success) {
if (Data.Estimate !== undefined) {
// Create a Html Table Row from the Estimate.
// Append the Row to the Table.
// Hide the Dialog.
} else {
alert("No Error Occured; however, the Creation of the Estimate was unsuccessful. Please Try Again.");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("An Error Occured. \n" + thrownError + "\n" + xhr.status);
}
});
}
Estimate Class
public class Estimate
{
public Int32 ID { get; set; }
public String JobDifficulty { get; set; }
public String Type { get; set; }
public String Name { get; set; }
public Unit NetUplift { get; set; }
public Unit JoistSpacing { get; set; }
public String DrawingLocation { get; set; }
}
Unit Class
public class Unit
{
public String Value { get; set; }
public Type DataType { get; set; }
public String UnitOfMeasure { get; set; }
public Unit(Type DataType, String Value, String UnitOfMeasure)
{
this.Value = Value;
this.DataType = DataType;
this.UnitOfMeasure = UnitOfMeasure;
}
}
Currently the action CreateEstimate(Estimate Est) recieves the data submitted except for sub-object values such as Unit (Estimate.NetUplift). How do I tell it to map NetUplift to Estimate.NetUplift.Value, and the two commented out input fields to NetUplift.DataType/NetUplift.UnitOfMeasure?
Is there a way to have the server just know that it should be mapped that way or do I have to do it before sending the form to the server?
You could try this:
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var estimate = $("#form-create-estimate").serializeToObject();