ASP.NET MVC4 View Model Parameter Null when Posted - asp.net-mvc-4

I want to use a view model as input to an Edit form. Call it -
public class StudentEditViewModel
{
}
My Edit action method creates the object and passes it to the Edit view, which has #model set to StudentEditViewModel. This works fine - all data is displayed as expected.
BUT, when I post the changes (using ) things fall apart. Here is the skeleton of my action handler:
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
}
The problem is that "student" is null. All the online examples appear to do it this way, but I'm obviously missing something. Can anyone help me out?
I'll be happy to provide more details if necessary. Thanks in advance.

Your StudentEditViewModel needs properties (E.g public string name { get; set;}) because the StudentEditViewModel should have a property basis for it to have a value and in your view, use the basic LINQ syntax
using(Html.BeginForm())
{
#html.TextBoxFor(u => u.name)
<input type="submit"/>
}
Try adding also with a non-Data annotation ActionResult and check out the breakpoints. This was my mistake before when I tried to program. Hope I can help you.

Are you using Explicitly typed View Model? In this case you can do it by jquery as follows:
$("#btnSave").click(function (event) {
event.preventDefault();
if ($("#form1").valid()) {
var formInput = $('#form1').serializeObject();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'your controller action url be here',
data: JSON.stringify(formInput)
})
.done(function (data, textStatus, jqXHR) {
showMsg('page-message', 'success', 'Success!', 'The item was saved.');
$('#PriorityDateId').val(data);
window.location.href = 'after save where you want to redirect(give url)';
})
.fail(function (jqXHR, textStatus, errorThrown) {
showResponse('page-message', 'error', 'Error!', jqXHR.responseText);
});
}
});
If need more info, let me know..

Your model should contain some properties like so:
model:
public class StudentEditViewModel
{
//Sample Properties
public string Name{get;set;}
public int Age {get;set;}
}
And your view should look something like this.
#model Nameofyourproject.Model.StudentEditViewModel
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name) // this where you will enter a value for the Name property
#Html.LabelFor(m => m.Age)
#Html.TextBoxFor(m => m.Age) // this where you will enter a value for the Age property
<input type="submit"/> //this will submit the values to your action method.
}
you will be able to get this values now in your action method
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
var name = student.Name;
var age = student.Age;
}

Related

asp.net MVC autocomplete with Html.TextBoxFor

I am modifying a preexisting application. I am trying to add the jquery autocomplete functionality. I have it working and calling the controller but the problem is the name attribute in the input field is "someClass.someMethod" so because I can't put this in the controller parameter like this, but still want to satisfy asp.net's Model Binding rules, what can I do?
Controller:
public JsonResult GetPs(string pN, PSModel pS)
{
List<string> pNs = null;
pNs= pS.PEntryBL.BusinessLayerPS.PS
.Where(x => x.Text.StartsWith(pN)).Select(y => y.Text).ToList();
return Json(pNs, JsonRequestBehavior.AllowGet);
}
View:
$(function () {
$("#autoCompletePNBox").autocomplete({
source: '#Url.Action("GetPs", "PS", new {pS = #Model})'
});
});
In Form:
#Html.Label("Scan PN: ", new { #class = "DFont"})
#Html.TextBoxFor(r => r.PEntryBL.PS, new { #class = "pageFont", id = "autoCompletePNBox" })
Using This Post
I was able to get it working by grabbing the value of the input field and passing it on each function call (or each time a user enters a character).
Now when the user selects the item from the autocomplete list, and selects submit then the frameworks form model binding behind the scenes will still work as originally implemented.
Here is the jquery code change:
<script type="text/javascript">
$(function () {
var src = '#Url.Action("GetPs", "PS", new {pS = #Model})'
$("#autoCompletePNBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
pN: $("#autoCompletePNBox").val()
},
success: function (data) {
response(data);
}
});
}
});
});
I couldn't figure this out right away as my Jquery skills are not very strong. Hopefully this helps someone.

how to pass value ember view to controller

I am new in pretty ember js development .
I have done view below code
{{view "select" content=model prompt="Please select a name" selectionBinding="" optionValuePath="content.body" optionLabelPath="content.title"}}
using following Json
posts = [{
title: "Raja",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
and Router
App.InRoute = Ember.Route.extend({
model: function () {
return posts;
}
});
My Requirement is passing that combo box selected value to controller
App.InController = Ember.Controller.extend({
alert("combobox selected item")
});
And how an i access that value apicontoller in .net mvc 4
public class ValuesController : ApiController
{
string value= combo box selected value
}
Your "select" view's value attribute needs to be bound to a property on the controller:
add the following to your view's attributes: value=selectedItem
In your controller:
Add "selectedItem"
App.InRoute = Ember.Route.extend({
selectedItem: null,
model: function () {
return posts;
}
});
Now your all set to send it to your Api end point. You could create an action handler and make it happen there. Here is a quick example:
App.InRoute = Ember.Route.extend({
selectedItem: null,
model: function () {
return posts;
},
actions: {
submit: function(){
$.ajax('/api/yourEndPoint', {type: 'POST', data: {body: this.get('selectedItem')} })
}
}
});
In your Handlebars template
<button {[action 'submit'}}>Submit</button>
In your .NET API Controller
public IHTTPActionResult Post(string body){
//.NET's Model Binder will correctly pull out the value of the body keyvalue pair.
//Now do with "body" as you will.
}
You should really look into using Ember-Data, it's freaking awesome.
You only need to set the selectionBinding="someModelAttribute" and the two way data binding will take care of setting the selected value on the model.

Can not find a way to check or uncheck checkbox in my view

I have a partial view ,which I throw to another view ,In my partial view there is a checkbox which is checked by default I want to change its current (checked/unchecked) option from main view. Here is my partial view code:
<td class="sevenCol" name="sevenCol">
<input type="checkbox" checked/>
</td>
Below shows partial view content:
$("#btnSubmit").click(function () {
var mobnum = $("#mobNo").val();
var message = $("#txtMessage").val();
alert(mobnum);
$.ajax({
url: "SmsSendFromOneToOne",
type: "POST",
data: { contactList: mobnum, message: message },
success: function (data) {
$("#gridGenerate").html(data);
}
});
});
Below verifies checkbox is checked or unchecked but it always returns true so how can I fix this?
$("#sendbtn").click(function () {![enter image description here][1]
var maskId = $("#MASKLIST").val();
var campaignName = $("#campaignName").val();
var dataArray = {};
$(".loadingmessage").show();
$("#gridGenerate tr").each(function (iii, val) {
var trId = $(this).attr("id");
var isChecked = $('td[name=sevenCol]').find('input[type="checkbox"]').is(':checked');
//alert(isChecked);
if (isChecked) {
dataArray[iii] = {
'mobile': $(this).find(".secondCol").text(),
'message': $(this).find(".thirdCol").text(),
'type': $(this).find(".fifthCol").text()
};
}
});
Controller:
[HttpPost]
public ActionResult SmsSendFromOneToOne(string contactList, string message)
{
IList<GridPanel> cellInfoForForm1 = _smsService.GetForm1ForViewing(contactList, message);
return PartialView("partialGridPanel", cellInfoForForm1);
}
Thanks
it is a lot simpler if you put the selector directly on the field. try adding a class to your checkbox
<input type="checkbox" class="mobileCheck" checked/>
then in your script you can replace
var isChecked = $('td[name=sevenCol]').find('input[type="checkbox"]').is(':checked');
with
var isChecked = $('.mobileCheck').is(':checked');
Finally got my answer ,As i am binding a partial view and checkbox exits in it so i have to use jquery .live( events, data, handler(eventObject) )to solve the issue ..
$( selector ).live( events, data, handler );
Again thanks for responding

MVC How to handel submit button on dynamically added partialview

Hi I have just started MVC Programming, so pls excuse my noob question.
I have a Index View with dropdown. And According to the dropdown value, I have added a partial view '_create' in ContentDiv of Index using jquery.
$('#CreateButton').click(function (e) {
$("#ContentDiv").load('/Controller/_Create?Id=' + $("#DropDownList1").val());
});
So, now I am not sure how to handel submit button inside that partialview (_Create)
My _create form looks like:
#using (Html.BeginForm("_Create","controller", FormMethod.Post,
new { id = "addFormData", name="addFormData" }))
{
----------
----------
<p>
<input type="submit" value="Create" />
</p>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult _Create(WorkFieldModel entity, FormCollection p_form)
{
addFormValuetoDB();
return PartialView();
}
And One more thing; how to maintain viewstate of dynamically added partial view after postback.
Any Help will be highly appreciated.
You could use an AJAX request to submit the form to avoid performing a full postback to the server and loosing the context:
$('#CreateButton').click(function (e) {
var data = { id: $("#DropDownList1").val() };
$("#ContentDiv").load('/Controller/_Create', data, function() {
$('#addFormData').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Thanks for submitting the form');
}
});
return false;
});
});
});
Since your HttpPost controller action returns a PartialView you could use this information in the success callback of the form submit and inject the result somewhere in the DOM.

Ajax.ActionLink parameter from DropDownList

I have the following view part:
<div class="editor-label">
#Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Type, ElangWeb.Helpers.ModelHelpers.GetExerciseTypes())
</div>
I want to have a link which will generate some partialview based on my model's Type property which is an Enum (I return different partial views based on the type),
I've added the following link:
#Ajax.ActionLink("AddExerciseItem",
"AddExerciseItem",
"Exercise",
new { type=#Model.Type},
new AjaxOptions() { HttpMethod="GET", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId="ExerciseItems"})
My controller action is defined as follows:
public ActionResult AddExerciseItem(ExerciseType type)
{
return PartialView("ExerciseItemOption", new ExerciseItemOption());
}
I however does not work because I have the exeption "Object reference not set to an instance of an object" for my Model. How to resolve this issue?
You could use a normal link:
#Html.ActionLink(
"AddExerciseItem",
"AddExerciseItem",
"Exercise",
null,
new { id = "add" }
)
that you could unobtrusively AJAXify:
// When the DOM is ready
$(function() {
// Subscribe to the click event of the anchor
$('#add').click(function() {
// When the anchor is clicked get the currently
// selected type from the dropdown list.
var type = $('#Type').val();
// and send an AJAX request to the controller action that
// this link is pointing to:
$.ajax({
url: this.href,
type: 'GET',
// and include the type as query string parameter
data: { type: type },
// and make sure that you disable the cache because some
// browsers might cache GET requests
cache: false,
success: function(result) {
// When the AJAX request succeeds prepend the resulting
// markup to the DOM the same way you were doing in your
// AJAX.ActionLink
$('#ExerciseItems').prepend(result);
}
});
return false;
});
});
Now your AddExerciseItem controller action could take the type parameter:
public ActionResult AddExerciseItem(string type)
{
...
}