return type is getting null while having data passed in it - sql

this is my form I am using mvc in VS2013 where I am little confused about whats happening here, it is returning me empty fields while I am passing required data, although it is ok when fields are empty but when it has data in it it should be fired a successfully sent it but it is not working
guys please help me to get my this code working
View
#using (Html.BeginForm("RegUser", "User", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal custom_frmHorizontal">
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
#*#Html.HiddenFor(model => model.Subscription)*#
#Html.TextBoxFor(model => model.CompanyName, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company Name", #id = "txtName" })
#Html.ValidationMessageFor(model => model.CompanyName, null, new { #class = "text-danger" })
<span id="ern" class="field-validation-error text-danger" data-valmsg-for="CompanyName" data-valmsg-replace="true" style="display:none;"></span>
</div>
</div>
<div class="form-group">
#*<label class="col-md-4 control-label" for="textinput">Email Address :</label>*#
<div class="col-md-12">
#*<input id="textinput" name="textinput" type="text" placeholder="Email Address" class="form-control input-md">*#
#Html.TextBoxFor(model => model.Email, new { #class = "form-control input-md", #style = "background-color:transparent !important;", #autocomplete = "off", #placeholder = "Email Address", #id = "txtemail" })
#Html.ValidationMessageFor(model => model.Email, null, new { #class = "text-danger" })
<span id="ere" class=" field-validation-error text-danger" data-valmsg-for="Email" data-valmsg-replace="true" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Mobile, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Phone Number", #id = "txtMobile" })
#Html.ValidationMessageFor(model => model.Mobile, null, new { #class = "text-danger" })
<span id="ermob" class=" field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.CRN, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company CRN", #id = "txtCrn" })
#Html.ValidationMessageFor(model => model.CRN, null, new { #class = "text-danger" })
<span id="ercrn" class=" field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.EmpStrength, new { #class = "form-control", #autocomplete = "off", #placeholder = "Employees Strength", #id = "txtEmpStr" })
#Html.ValidationMessageFor(model => model.EmpStrength, null, new { #class = "text-danger" })
<span id="eremp" class="field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Address, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company Address", #id = "txtCadrs" })
#Html.ValidationMessageFor(model => model.Address, null, new { #class = "text-danger" })
<span id="eradrs" class="errmsg field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group btn_wrap">
<div class="col-md-12">
<button id="formSubmit" value="Submit" type="submit" class="btnCutom1 btn btn-primary">Send Request<i class="far fa-paper-plane pl-3"></i></button>
</div>
</div>
</fieldset>
</div>
}
Jquery
$('#myForm').on('submit', function(event) {
var frmData = $("myForm");
event.preventDefault()
var name = document.getElementById('txtName').value;
var email = document.getElementById('txtemail').value;
var mobile = document.getElementById('txtMobile').value;
var crn = document.getElementById('txtCrn').value;
var emp = document.getElementById('txtEmpStr').value;
var adrs = document.getElementById('txtCadrs').value;
if (name.length == 0) {
//alert("Please insert Company Name");
$("#ern").text("Company name must required").fadeIn();
}
if (email.length == 0) {
$("#ere").text("Please insert email address").fadeIn();
}
if (mobile.length == 0) {
//alert("Please insert Mobile Number");
$("#ermob").text("Please insert Mobile Number").fadeIn();
}
if (crn.length == 0) {
//alert("Please insert CRN");
$("#ercrn").text("Please insert CRN").fadeIn();
}
if (emp.length == 0) {
//alert("Please insert Employees");
$("#eremp").text("Please insert Employees Strength").fadeIn();
}
if (adrs.length == 0) {
//alert("Please insert Address");
$("#eradrs").text("Please insert Company Address").fadeIn();
} else {
//var frmData = $("myForm");
//e.preventDefault();
$.ajax({
type: "Post",
ContentType: "application/json; charset=utf-8",
data: "{frmData:" + JSON.stringify(frmData) + "}",
// url: "pricing/Index",
success: function(data) {
alert("sent successfully:" + data);
location.window.href = "RegUser/User";
},
error: function(result) {
//$form = $(this);
alert("something went wrong");
}
});
}
});
Controller
public class UserController : Controller
{
//
// GET: /User/
[HttpGet]
public ActionResult RegUser(int id=0)
{
UserDtl userModel = new UserDtl();
return View(userModel);
}
[HttpPost]
public ActionResult RegUser(UserDtl userModel, string CompanyName, string Email, string CRN, string EmpStrength, string Mobile, string Address)
{
try
{
using (DbModels dbModel = new DbModels())
{
dbModel.UserDtls.Add(userModel);
dbModel.SaveChanges();
}
if (ModelState.IsValid)
{
var senderemail = new MailAddress("shakil.7878#gmail.com", "deem-admin");
var receiveremail = new MailAddress(Email, "New Request");
var password = "inDia123#";
var sub = CompanyName;
string bodyText = string.Format("<table border='0' cellpadding='0' cellspacing='0' style='width:600px; background:#efefef;'> <tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/mh.jpg' /></center></td></tr><tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/ms.jpg' /></center></td></tr> <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'><b>New Request</b></td><td> </td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Company Name: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{0}</td> </tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Email Address: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{1}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Registration No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{2}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Employees Strength</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{3}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Mobile No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{4}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Address</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{5}</td> </tr> <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr> <tr><td style='background:#303030; height:30px;' colspan='2'><center><a style='color:#ffffff; text-align:center; font-family:Arial; font-size:12px;' href='#' target='_blank'>www.deem.sa</a></center></td></tr> </table>", CompanyName, Email, CRN, EmpStrength, Mobile, Address);
var body = bodyText;
var smtp = new SmtpClient
{Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderemail.Address, password)};
var mess = new MailMessage(senderemail, receiveremail)
{Subject = sub,
Body = body,
IsBodyHtml = true};
smtp.Send(mess);
ModelState.Clear();
ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";
return View();
}
//ModelState.Clear();
//ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";
}
catch (Exception ex)
{
}
return View("RegUser", new UserDtl());
}
}

You can't specify the DOM id for your input elements like this (#id = "txtName"). The id is automatically generated by the framework. If you view the source in your browser, you will see these elements have been rendered with 2 ids. This is invalid HTML, causing your breakage.
There are accepted answers to other questions here on SO basically saying you can capitalize #id to fix this (i.e. #Id), but the users providing these answers don't understand how the attributes on these elements are generated, and are simply observing a side effect of a hack that is not actually guaranteed to work in any scenario, though it may happen to work in a few browsers under certain conditions right now.
Instead, remove any use of "#id=", and use the #Html.IdFor() helper to determine the assigned ID. For example:
<script>
var myId = "#Html.IdFor(m => m.CompanyName)";
</script>
You would then use this Javascript variable (e.g. myId) in place of the ID you invented ("txtName") in the rest of your code .. for example, you'd change this:
var name = document.getElementById('txtName').value;
To this:
var name = document.getElementById(myId).value;
And since you're using jQuery, you may alternatively express this as follows:
var name = $("#" + myId).val();
Then the generated HTML will be valid and your form will post as expected.

$('#myForm').on('submit', function (event) {
var frmData = $("myForm");
// event.preventDefault()
var myCn = "#Html.IdFor(m => m.CompanyName)";
var myEm = "#Html.IdFor(m => m.Email)";
var myMo = "#Html.IdFor(m => m.Mobile)";
var myCr = "#Html.IdFor(m => m.CRN)";
var myEp = "#Html.IdFor(m => m.EmpStrength)";
var myAd = "#Html.IdFor(m => m.Address)";
var name = document.getElementById(myCn).value;
var email = document.getElementById(myEm).value;
var mobile = document.getElementById(myMo).value;
var crn = document.getElementById(myCr).value;
var emp = document.getElementById(myEp).value;
var adrs = document.getElementById(myAd).value;
//var name = $("#" + myCn).val();
//var email = $("#" + myEm).val();
//var mobile = $("#" + myMo).val();
//var crn = $("#" + myCr).val();
//var emp = $("#" + myEp).val();
//var adrs = $("#" + myAd).val();
if (name.length == 0) {
//alert("Please insert Company Name");
$("#ern").text("Company name must required").fadeIn();
} if (email.length == 0) {
$("#ere").text("Please insert email address").fadeIn();
} if (mobile.length == 0) {
//alert("Please insert Mobile Number");
$("#ermob").text("Please insert Mobile Number").fadeIn();
}
if (crn.length == 0) {
//alert("Please insert CRN");
$("#ercrn").text("Please insert CRN").fadeIn();
}
if (emp.length == 0) {
//alert("Please insert Employees");
$("#eremp").text("Please insert Employees Strength").fadeIn();
}
if (adrs.length == 0) {
//alert("Please insert Address");
$("#eradrs").text("Please insert Company Address").fadeIn();
}
else {
//var frmData = $("myForm");
//e.preventDefault();
$.ajax({
type: "Post",
ContentType: "application/json; charset=utf-8",
data: "{frmData:" + JSON.stringify(frmData) + "}",
// url: "pricing/Index",
success: function (data) {
alert("sent successfully:" + data);
location.window.href = "RegUser/User";
},
error: function (result) {
//$form = $(this);
alert("something went wrong");
}
});
}
});

Related

Razor Page Cascade Datatables by Dropdown

i have a dropdown list and i want to reload the datatable once i change the dropdown please note that the Checkbox field postback the page as well to update the database below is the cs file and will post the cshtml after
public class IndexModel : PageModel
{
private readonly IpponAcademy.Models.IJAContext _context;
public List<SelectListItem> judokaGroupList { get; set; }
[BindProperty]
public Boolean IsAttend { get; set; }
public IList<tbl_Judoka> tbl_Judoka { get;set; }
public IndexModel(IpponAcademy.Models.IJAContext context)
{
_context = context;
}
public void OnGet(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
}
below is the cshtml file, I'd appreciate finding a simple way to do refresh the datatable with the new selected field from the dropdown
#page
#model IpponAcademy.Pages.Attendance.IndexModel
#{
ViewData["Title"] = "Index";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<form method="post">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" asp-items="Model.judokaGroupList"></select>
#*onchange="alert(#Model.judokaGroupList)"*#
</div>
<table id="taskDt" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>
Attended
</th>
<th>
Code
</th>
<th>
Image
</th>
<th>
Judoka
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.tbl_Judoka)
{
var imagePath = #"UploadedFiles/" + item.J_Image;
<tr>
<td>
<input type="hidden" name="J_GUID" id="J_GUID" value="#item.J_GUID" />
<input asp-for="IsAttend" name="IsAttend" id="IsAttend" type="checkbox" onclick="this.form.submit()" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Code)
</td>
<td align="center">
<img src="#imagePath" alt="Judoka" width="50" height="50" class="rounded-circle mr-1" onclick="return LoadDiv(this.src);" style="cursor: pointer" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Name)
</td>
</tr>
}
</tbody>
</table>
</form>
#section scripts{
<script>
var table;
function LoadData() {
//alert('in');
table = $("#taskDt").DataTable({
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
}
$(document).ready(function () {
LoadData();
})
$("#ddlGroup").change(function () {
alert('DDLGroup');
//table.ajax.url("/Attendance/Index?handler=GET&Id=" + $("#ddlGroup Option:Selected").val()).load();
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
</script>
}
I think using window.location.href has been a simple enough way to refresh the datatable.Just one thing you need to improve,OnGet and OnGetJudoka method are the same,why not using just one method.
Change:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
To:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?Id=' + $("#ddlGroup Option:Selected").val();
});
If you must use another way,you could use form.submit():
Note:Be sure add name="id",otherwise the parameter will not bind to the backend.
<form method="post" asp-page-handler="Judoka">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" name="id" asp-items="Model.judokaGroupList"
onchange="this.form.submit()"></select>
</div>
</form>
Backend code:
Change:
public void OnGetJudoka(Guid? id)
To:
public void OnPostJudoka(Guid? id)
BTW,I also have a suggestion that you'd better maintain the selected value after postback :
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
//maintain the selected value after post back...
var selectedValue= judokaGroupList.Where(a => a.Value == id.ToString()).FirstOrDefault();
selectedValue.Selected = true;
//...
}

How fix not working ActionResult Update in NET Core?

I'm learning about .NET Core and I'm using code from this tutorial. But my update sql is not working.
Here is the index view code:
public ActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = db.Chars.ToList();
Chars Chars = db.Chars.Find(id);
return View(Chars);
}
As for now it work I see results from sql and here is the updated part:
public ActionResult Update(Chars Chars)
{
if (ModelState.IsValid)
{
db.Entry(Chars).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
Here is index.cshtml part:
#using (Html.BeginForm()
{
#foreach (var item in (IEnumerable<MVC__test_2.Chars>)ViewBag.Name)
{
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(modelItem => item.CharName, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(modelItem => item.CharID, new { id = item.CharID })
</div>
</div>
#Html.ActionLink("Index", "Index", new { id = item.CharID })
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
}
}
According to the tutorial you provided , I made a demo to test and it updated the data well. The following is the working example , you could refer to and make the modification as per your need .
Model
public class Description
{
public int Id { get; set; }
public string Display { get; set; }
}
Controller
public IActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = _context.Description.ToList();
Description description= _context.Description.Find(id);
return View(description);
}
public ActionResult Update(Description description)
{
if (ModelState.IsValid)
{
_context.Entry(description).State = EntityState.Modified;
_context.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
Index.cshtml , you should hide the id of the modified data in the modification section.
#model WebApplication1.Models.Description
#using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
#foreach (var item in (IEnumerable<WebApplication1.Models.Description >)ViewBag.Name)
{
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(modelItem => item.Display, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(modelItem => item.Id, new { id = item.Id })
</div>
</div>
#Html.ActionLink("Edit", "Index", new { id = item.Id })
}
// Create or Update data
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<fieldset>
<legend> <b>Entry Screen</b></legend>
<div class="form-group">
#Html.LabelFor(model => model.Display, new { #class = "control-label col-md-2" })
#Html.HiddenFor(model => model.Id)
<div class="col-md-10">
#Html.EditorFor(model => model.Display)
#Html.ValidationMessageFor(model => model.Display)
</div>
</div>
<div class="form-group">
<p>
<input type="submit" value="Create" name="Create"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
</p>
</div>
</fieldset>
</div>
}

File upload in MVC 5 when used in bootstrap modal returns null

I'm trying to allow file uploading on modal popup using bootstrap modal popup.
But it always returns null for type = "file"
I've tried following solutions but no luck:
File upload in MVC when used in bootstrap modal returns null
it always return null. If I run this directly as separate page then it works fine but only having problem with popup.
I tried to change the content type on ajax but then its giving me this error "required anti-forgery form field __requestverificationtoken is not present"
I've tested what does page post using development tools:
enter image description here
here are my codes:
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind(Include = "ID,FileName,Link,SourceType,Comments,SourceDate,DateCreated,DateModified,ProjectID")] ProjectSource projectSource, HttpPostedFileBase uploadFile)
{
if (ModelState.IsValid)
{
//upload method 1
var fileSavePath = "";
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
fileSavePath = (HttpContext.Server.MapPath("~/xyz/") + httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
//upload method 2
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/xyz/"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
db.ProjectSources.Add(projectSource);
await db.SaveChangesAsync();
return " File : " + ViewBag.Message + " == " + fileSavePath;
}
return " File : " + ViewBag.Message +" === "+sb.ToString();
}
view:
#model CharterPortal.Models.ProjectSource
#{
Layout = "";
#Scripts.Render("~/Scripts/jquery-2.2.3.min.js")
#Scripts.Render("~/Scripts/moment.min.js")
#Scripts.Render("~/Scripts/bootstrap.min.js")
#Scripts.Render("~/Scripts/bootstrap-datetimepicker.min.js")
#Scripts.Render("~/Scripts/bootstrap.fd.js")
}
×
Add new Source
#using (Html.BeginForm("Create", "ProjectSource", FormMethod.Post, new { enctype = "multipart/form-data" , #id="ajaxForm"}))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#*#Html.ValidationSummary(true, "", new { #class = "text-danger" })*#
<div class="form-group">
#Html.Label("Source file", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
#*<input type="file" name="uploadFile" />*#
#Html.TextBox("uploadFile",null, new { #class = "form-control", type = "file" })
#*Add file*#
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
<div class="col-md-10" id="files" style="padding-left:40px;">
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.Link, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.Link, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Link, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.SourceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SourceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceDate, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.EditorFor(model => model.SourceDate, new { htmlAttributes = new { #class = "form-control datepicker datefield" } })
#Html.ValidationMessageFor(model => model.SourceDate, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-med btn-orange" data-dismiss="modal">Cancel</button>
<input class="btn btn-med btn-orange" type="submit" name="submit" value="Add" />
</div>
}
ajax:
$('form', dialog).submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
contentType:this.enctype,
success: function (result) {
if (result) {
alert(result)
//Refresh
} else {
alert(result)
}
}
});
return false;
});
I hope to get good working solution for this:
thanks in advance for your time.
Thanks
Ive been using this block of code to solve this problem and ModelState.IsValid in partials for about a year. cheers.
$(function () {
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
$('#modal').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($(this));
});
$('#modal').on('hidden.bs.modal', function () {
$('#spinner').remove();
});
$.ajaxSetup({ cache: false });
});

How do i send the data to edit boxes on the same page?

i have the following page generated
when i click the Edit link, the record data must be sent to the input boxes on teh same page (without refreshing the page)
currently i have the controller code and views
controller: ProductCategory
public class ProductCategoryController : Controller
{
//
// GET: /ProductCategory/
TUDBEntities _db = new TUDBEntities();
public ActionResult Index(string Code)
{
var categories = _db.mt_ProductCategories
.Where(pc => Code == "" || Code == null|| pc.CatCode == Code)
.Select(
c => new ProductCategory {
Id = c.Id,
CategoryCode = c.CatCode,
Name = c.CatName,
Url = c.Url
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
[HttpPost]
public ActionResult Save(ProductCategory userData)
{
try
{
if (ModelState.IsValid)
{
mt_ProductCategories cat = new mt_ProductCategories { CatCode = userData.CategoryCode, CatName = userData.Name };
// TODO: Add insert logic here
_db.mt_ProductCategories.Add(cat);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
var category = _db.mt_ProductCategories
.Where(pc => pc.Id == id)
.Select(pc => new ProductCategory
{ Id=pc.Id, CategoryCode=pc.CatCode,Name=pc.CatName }).ToList();
return RedirectToAction("Index", category);
}
}
Index view
#model IEnumerable<eComm1.Models.ProductCategory>
#using(Ajax.BeginForm("Save", "ProductCategory",
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="prod-grid",
InsertionMode=InsertionMode.Replace,
OnSuccess="loaddivdata"
}))
{
<fieldset class="form-group">
<label for="Code">Category Code</label>
<input type="text" class="form-control focus" id="Code" name="CategoryCode" placeholder="Product category code" >
</fieldset>
<fieldset class="form-group">
<label for="ProdName">Product Name</label>
<input type="text" class="form-control" id="ProdName" name="Name" placeholder="Product Name">
</fieldset>
<button type="Submit" class="btn btn-primary">Save</button>
}
<hr />
<div id="prod-grid">
#Html.Partial("_ProductCategoryList", #Model)
</div>
<script type="text/javascript">
$(function () {
$('.focus :input').focus();
});
function loaddivdata() {
$('#prod-grid').html();
$('#Code, #ProdName').val('');
};
// $('#prod-grid').load(function () {
// $.ajax({
// url:'ProductCategoryController/Index',
// method:'GET',
// type:'application/html',
// success: function () { alert('called');}
// });
// });
//});
</script>
Partial View: _ProductCategoryList
#model IEnumerable<eComm1.Models.ProductCategory>
<div class="panel panel-default">
#if (Model.Count() == 0) { <div class="panel-heading">Product Categories - <span style='color:red;font-weight:bold' >0 RESULTS FOUND</span></div>
}else{
<!-- Default panel contents -->
<div class="panel-heading">Product Categories</div>
}
<!-- Table -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CategoryCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#*#Html.beActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })*#
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id=item.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", UpdateTargetId="", OnSuccess="loadformdata"})
</td>
</tr>
}
</table>
</div>
How do i modify my code to send data those input control and in my code how do i create hidden field for Id value so it can be send to the Edit(collection, int id) action to update the record?
for Stephen Muecke, i have added my jquery files through the bundles
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/ecomm").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-2.1.4.min.js",
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap.min.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"
));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/bootstrap.css",
"~/Content/style.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
In the partial view
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id = item.Id }, new AjaxOptions { HttpMethod = "GET", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", OnSuccess="loadformdata"})
in the index view the following js function:
function loadformdata() {
var cells = $(this).closest('tr').children('td');
alert(cells.eq(0).text());
//$('#Code').val(cells.eq(0).text());
//$('#ProdName').val(cells.eq(1).text());
}
To: Stephen Muecke:
i have removed above loadformdata() and put everything as you said. this youtube video shows the problem that still does not call that click event
To: Steven Meucke:
there's still no luck, for ease i have added a alert() in the function and the alert() won't show. Here is the video
Give you 'Edit' link a class name (say) class="edit" and handle its .click() event to update the form controls
$('.edit').click(function() {
var cells = $(this).closest('tr').children('td');
$('#Code').val(cells.eq(0).text());
$('#ProdName').val(cells.eq(1).text());
return false; // cancel the default redirect
});
Side note: You could just replace the ActionLink() code with Edit and the return false; line is not necessary.
write script for ajax call:
$('#edit').click(function () {
// var data = {here you will pass item.id }
$.ajax({
url:'ProductCategoryController/Edit',
data: {id : data}
method:'GET',
success: function (data) {
//clear html page here
//reload html page by passing 'data' passes in function
//e.g. suppose html page id is 'xyz' then $("#xyz").html(data)
}
});
});

passing value via ajax to controller action having null httppostedbasefile

My Razor html:
#using (Html.BeginForm("CreateTestinomialPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Fill Form</legend>
#Html.HiddenFor(m => m.PostedTypeId)
<div class="editor-label">
#Html.DisplayName("Image Upload")
</div>
<div class="editor-field" >
#*<input type="file" name="file" id="file" />*#
#Html.TextBoxFor(m => m.file,new{type="file"})
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Postedby)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Postedby)
#Html.ValidationMessageFor(model => model.Postedby)
</div>
<p>
<input type="submit" value="Create" />
</p>
<div id="result"></div>
</fieldset>
}
My scripts:
<script type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
},
complete: function () {
$('form').each(function () {
this.reset(); //Here form fields will be cleared.
});
},
});
}
return false;
});
});
</script>
my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateTestinomialPage(TestinomialsModels models,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int maxcontentlength = 1024 * 1024 * 3;
string[] AllowedExtension = new string[] { ".jpg", ".gif", ".png" };
if (!AllowedExtension.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedExtension));
}
else if (file.ContentLength > maxcontentlength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + maxcontentlength + " MB");
}
else
{
var filename = Path.GetFileName(models.file.FileName);
models.ImagePath = ConfigurationManager.AppSettings["ImagesavePath"].ToString() + filename;
postservices.AddTestinomailPost(models);
var path = Path.Combine(Server.MapPath("~/Content/Upload/Images"), filename);
models.file.SaveAs(path);
return Content("Successfully Submiited");
}
}
}
return Content("An error occur while saved Plese try again..");
}
There is controllerAction null httppostedbasefile..