code behind in newform.Aspx?
I have a list that must be filled with a bit of code behind (prepopulating some fields, and do a bit of work on the save button.)
What is the best way to do that ?
thx
Edit: I ended by creating a custom webpart on the default.aspx. In this web part I have a bunch of :
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<h3 class="ms-standardheader">
<nobr>Title<span class="ms-formvalidation"> *</span>
</nobr>
</h3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<SharePoint:FormField runat="server" id="fldTitle" ControlMode="New" FieldName="Title" ListId="{MyListID}" />
<SharePoint:FieldDescription runat="server" id="ff1description" FieldName="Title" ControlMode="New" ListId="{MyList开发者_如何转开发ID}"/>
</td>
</tr>
This is working, but I found this in a bit painfull because I have to read each form field in code behind :
private void Set(SPListItem item, string fieldInternalName, object fieldValue)
{
var field = item.Fields.GetFieldByInternalName(fieldInternalName);
item[fieldInternalName] = fieldValue;
}
protected void Btn_Ok_Click(object sender, EventArgs e)
{
SPWeb thisWeb = SPContext.Current.Web;
SPList myList= thisWeb.Lists["mylist"];
SPListItem newItem;
newItem= myList.Items.Add();
var router = thisWeb.EnsureUser(@"myuser");
Set(newItem, "Title", fldTitle.Value);
Set(newItem, "OtherField", fldOther.Value);
Set(newItem, "AnotherField", GetFromBusinessLogic());
SPUtility.Redirect(thisWeb.Url, SPRedirectFlags.Default, System.Web.HttpContext.Current);
newItem.Update();
}
Is there any way to wrap all of this in a custom form container ? Maybe a custom ListFormWebPart with inner templates and code-behind events ?
You can follow the suggestion here to add in the code-behind.
BUT even if you put in a code-behind file, you still cannot reference the controls (fields, save buttons etc) on the form from the code-behind.
I would suggest writing up a web service (asmx or WCF) and host it on the Sharepoint instance. You can then use javascript and AJAX calls to perform initialization and validation.
精彩评论