Ajax.BeginForm redirects action page(MVC 4) - asp.net-mvc

I use 'Ajax.BeginForm' in my application,but for some reason my form is redirecting to {controller}/{action} with right json data instead of start {OnComplete = "Add_OnComplete"}:
View:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "Add_OnComplete"}))
{
<fieldset>
<legend>Add</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FullName)
#Html.ValidationMessageFor(model => model.FullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Status)
#Html.ValidationMessageFor(model => model.Status)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<script type="text/javascript">
function Add_OnComplete(context) {
var JsonAdd = context.get_response().get_object();
if (JsonAdd.Success) {
//TODO
}
}
</script>
Controller:
public PartialViewResult Create()
{
return PartialView();
}
[HttpPost]
public JsonResult Create(Subscribe model)
{
if (ModelState.IsValid)
{
_entity.CreateSubscribe(model, SubscribeStatus.Customer.GetHashCode());
var message = new Message(MailSubject, MailBody, model.Email);
message.Send();
}
return Json(new
{
Success = true,
Message = "The person has been added!"
});
}
What I do wrong ? And what am I missing?
Thanks.

Remove that get_response().get_object() stuff.
Use just context.Success

Related

ViewModel does not populate input fields

I have a ViewModel that is used for an edit View. When the data is returned, the ID of the item to be edited does not display on the edit View.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
return View(viewModel);
}
Should I be returning something different to the View?
ViewModel:
public class ParcelEditViewModel
{
public Parcel parcel { get; set; }
public int id { get; set; }
public IEnumerable<SelectListItem> TrackStatus { get; set; }
public ParcelEditViewModel()
{
parcel = new Parcel();
TrackStatus = new List<SelectListItem>
{
new SelectListItem
{
Value = "AwaitingCollection",
Text = "Awaiting Collection"
},
new SelectListItem
{
Value = "OutForDelivery",
Text = "Out For Delivery"
},
new SelectListItem
{
Value = "Delivered",
Text = "Delivered"
}
};
}
public int ParcelStatus { get; set; }
}
View:
//#model ABC.Data.Parcel
#model Abc.ViewModels.ParcelEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Parcel</legend>
#Html.HiddenFor(model => model.parcel.id)
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Forename)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Forename)
#Html.ValidationMessageFor(model => model.parcel.Forename)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Surname)
#Html.ValidationMessageFor(model => model.parcel.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CompanyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CompanyName)
#Html.ValidationMessageFor(model => model.parcel.CompanyName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address1)
#Html.ValidationMessageFor(model => model.parcel.Address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address2)
#Html.ValidationMessageFor(model => model.parcel.Address2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address3)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address3)
#Html.ValidationMessageFor(model => model.parcel.Address3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Postcode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Postcode)
#Html.ValidationMessageFor(model => model.parcel.Postcode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParcelStatus)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.parcel.TrackingStatus, Model.TrackStatus)
#Html.ValidationMessageFor(model => model.ParcelStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.TrackingNumber)
#Html.ValidationMessageFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CustomerId)
#Html.ValidationMessageFor(model => model.parcel.CustomerId)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
You need to populate all of your view model's properties; not just the ID. The ParcelEditViewModel has no knowledge of what's in your database.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
// Populate other properties! These may not be right.
viewModel.ProductName = parcel.Title;
viewModel.RecipientName; = parcel.RecipientName;
return View(viewModel);
}
There are mapping libraries such as AutoMapper that can help to streamline this.

How auto retrieve data from database in mvc?

It is a create view page where i have insert supplier information and it is inserting data successfully. i want to get this data automatically when i will enter a name and it exist it will show all of the data in these field, if not exist then i will save to the table.
#model FCBook.Supplier
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Supplier</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SupplierName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SupplierName)
#Html.ValidationMessageFor(model => model.SupplierName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNo)
#Html.ValidationMessageFor(model => model.PhoneNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Area)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Area)
#Html.ValidationMessageFor(model => model.Area)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.District)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.District)
#Html.ValidationMessageFor(model => model.District)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Division)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Division)
#Html.ValidationMessageFor(model => model.Division)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My controller action to this create view is
public ActionResult Create()
{
return View();
}
//
// POST: /Supplier/Create
[HttpPost]
public ActionResult Create(Supplier collection)
{
try
{
// TODO: Add insert logic here
var db = new PetaPoco.Database("FCBook");
if (collection != null)
{
collection.Insert();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I think you want to look into using Remote validation. It can be triggered after a user enters a value into one of your fields. I'm using this approach to populate other fields upon such an event occurring.

What is the VB.NET equivalence of this razor syntax?

I'm really having issues with the lambda expressions.
#model CalculateSimpleInterest.Models.SimpleInterestModel
#{
ViewBag.Title = "SimpleInterest";
}
<h2>Calulate Simple Interest</h2>#using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",
new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))
{
<fieldset>
<legend>Calulate Simple Interest</legend><div id="div1"></div>
<div class="editor-label">
#Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Rate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Rate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Year)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Year)
</div>
<p>
<input type="submit" value="Calculate" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The syntax you are looking for is
#Html.YourHelperFor(Function(model), model.Property)
eg
<div class="editor-label">
#Html.LabelFor(Function(model), model.Amount)
</div>

Values in model are null or empty

I have this action method
[HttpPost]
public ActionResult CreateEsf(EsfLotDetailsModel model)
{
...
}
I have two properties in this model. One is a database POCO object and the other is a list. In the GET equivalent of this method, these values were all populated correctly, but on post these get set to null (the POCO) and empty (the list).
Why might this be?
My view is here
#using UI.Helpers
#model UI.Areas.Admin.Models.EsfLotDetailsModel
#{
ViewBag.Title = "Create Forward Lot";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/AdminDesignTheme/js/wl_Date.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/AdminDesignTheme/js/wl_Time.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.mousewheel.min.js")" type="text/javascript"></script>
#{
<script type="text/javascript">
$(document).ready(function () {
var options = {
dateFormat: "dd/mm/yy"
};
$('#Starts').wl_Date(options);
$('#Ends').wl_Date(options);
$('#startTime').wl_Time();
$('#endTime').wl_Time();
});
</script>
}
<p>#Html.ActionLink("Back to Item List", "Index","Inventory")</p>
#Html.ValidationSummary(true, "Please correct the errors and try again.")
#using (Html.BeginForm(new {model = #Model})) {
#Html.HiddenFor(model => model.Auction.InventoryReference)
#Html.HiddenFor(model => model.Auction.Title)
#Html.HiddenFor(model => model.Auction.Description)
<fieldset>
<legend></legend>
<label>ESF Lot Information</label>
<section>
#Html.LabelFor(model => model.Auction.Title)
<div> #Html.DisplayFor(model => model.Auction.Title)
#Html.ValidationMessageFor(model => model.Auction.Title) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.Description)
<div> #Html.DisplayFor(model => model.Auction.Description)
#Html.ValidationMessageFor(model => model.Auction.Description) </div>
</section>
#if (HttpContextHelper.IsUserAdmin())
{<section>
<label for="IsFeatured">Is Featured <i>(displayed in homepage)</i></label>
<div> #Html.CheckBoxFor(model => model.Auction.IsFeatured)
#Html.ValidationMessageFor(model => model.Auction.IsFeatured) </div>
</section>
}
else
{
<section>
<label for="IsFeatured">Is Featured <i>(displayed in homepage)</i></label>
<div> #Html.CheckBoxFor(model => model.Auction.IsFeatured, new { disabled = "disabled" }) (Contact Admin to make this a featured lot)
#Html.ValidationMessageFor(model => model.Auction.IsFeatured) </div>
</section>
}
#if (HttpContextHelper.IsUserAdmin())
{<section>
#Html.Label("VAT Applicable")
<div> #Html.CheckBoxFor(model => model.Auction.VatApplicable)
#Html.ValidationMessageFor(model => model.Auction.VatApplicable) </div>
</section>
}
else
{
<section>
#Html.Label("VAT Applicable")
<div> #Html.CheckBoxFor(model => model.Auction.VatApplicable, new { disabled = "disabled" }) (Contact Admin if it is not VATable)
#Html.ValidationMessageFor(model => model.Auction.VatApplicable) </div>
</section>
}
</fieldset>
<fieldset>
<legend></legend>
<label>Date and Time</label>
<section>
<label>Starts <em>(dd/mm/yy hh:mm)</em></label>
<div> <input type="text" class="date" id="Starts" />
<input type="text" class="time" data-connect="Starts" id="startTime" />
#Html.ValidationMessageFor(model => model.Auction.Starts) </div>
</section>
<section>
<label>Ends <em>(dd/mm/yy hh:mm)</em></label>
<div> <input type="text" class="date" id="Ends" />
<input type="text" class="time" data-connect="Ends" id="endTime" />
#Html.ValidationMessageFor(model => model.Auction.Ends) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.IsExtensible)
<div> #Html.CheckBoxFor(model => model.Auction.IsExtensible)
#Html.ValidationMessageFor(model => model.Auction.IsExtensible) </div>
</section>
</fieldset>
<fieldset>
<legend></legend>
<label>Bid Options</label>
<section>
#Html.LabelFor(model => model.Auction.StartingBid)
<div> #Html.TextBoxFor(model => model.Auction.StartingBid)
#Html.ValidationMessageFor(model => model.Auction.StartingBid) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.Reserve)
<div> #Html.TextBoxFor(model => model.Auction.Reserve)
#Html.ValidationMessageFor(model => model.Auction.Reserve) </div>
</section>
<section>
<label>Reserve Visible <em>(Displays as Reserve met or not met)</em></label>
<div> #Html.CheckBoxFor(model => model.Auction.ReserveVisible)
#Html.ValidationMessageFor(model => model.Auction.ReserveVisible) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.IsBidIncrementPercentual)
<div> #Html.CheckBoxFor(model => model.Auction.IsBidIncrementPercentual)
#Html.ValidationMessageFor(model => model.Auction.IsBidIncrementPercentual) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.BidIncrement)
<div> #Html.TextBoxFor(model => model.Auction.BidIncrement, new { #Value = 1m })
#Html.ValidationMessageFor(model => model.Auction.BidIncrement) </div>
</section>
<section>
#Html.LabelFor(model => model.AuctionEvents)
<div> #Html.DropDownList("Auction", Model.AuctionEvents, "Select auction", new { required = "required" })
#Html.ValidationMessageFor(model => model.AuctionEvents) </div>
</section>
<section>
<div><button>Create</button></div>
</section>
</fieldset>
}
<div>
#Html.ActionLink("Back to Item List", "Index","Inventory")
</div>
Add FormMethod = FormMethod.Post to your Html.BeginForm()
#using (Html.BeginForm("Action", "Controller",FormMethod.Post))
{
}
where is your submit button?
#using (Html.BeginForm("Action", "Controller",FormMethod.Post))
{
...
<input type="submit" value="submit" />
}
when you fill in the form, press the submit button, then enter in the [HttpPost] Method and value of Model will be filled.
None of these options worked. I put all the values in the POCO object separately in the model instead and removed the POCO object. No idea why it doesn't work.

ASP MVC3 how to add system current date?

I have form like
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
I want to insert system current date and time in the field of Date field. How can i do this. Model and cotroller are already create by scaffolding.
Insert this before you call the editor (assuming your property is a DateTime)
#{ Model.date = DateTime.Now; }
If your property is a string, call DateTime.Now.ToString().
You could set the default value in the corresponding controller action:
public ActionResult Index() {
return View(new SomeModel { date = DateTime.Now });
}
Change your code as mention below
#{ Model.date = DateTime.Now.ToString(); }
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>

Resources